Advanced - Book - Final-1 PDF
Advanced - Book - Final-1 PDF
Embedded Systems
Contents
Chapter 1 - Introduction to Embedded Electronics ........................................................................... 1
1.1 Embedded System .................................................................................................................. 1
1.1.1 Example of Embedded System........................................................................................ 2
1.1.2 Characteristics ................................................................................................................. 3
1.1.3 User interface.................................................................................................................. 3
1.1.4 Processors in embedded systems ................................................................................... 4
1.1.5 Peripherals ...................................................................................................................... 4
1.2 Microcontrollers...................................................................................................................... 4
1.2.1 What is a Microcontroller? ............................................................................................. 4
1.2.2 Microcontrollers vs. Microprocessors ............................................................................ 5
1.2.3 Development/Classification of microcontrollers (Invisible) ........................................... 5
1.2.4 Development of microprocessors (Visible) ..................................................................... 5
1.2.5 Internal Structure of a Microcontroller .......................................................................... 7
1.2.6 Harvard vs. Princeton Architecture................................................................................. 7
1.2.7 Princeton Architecture (Single memory interface) ......................................................... 8
1.2.8 Harvard Architecture (Separate Program and Data Memory interfaces) ....................... 9
1.3 Data Memory Organization .................................................................................................. 10
1.3.1 I/O Registers space in Harvard Architecture ................................................................. 11
1.4 CISC (Complex Instruction Set Computer) Processor Architecture ...................................... 12
1.5 RISC (Reduced Instruction Set Computer) Architecture Design ........................................... 12
1.6 RISC & CISC Architecture in Today's Computer Systems ...................................................... 13
1.7 Atmel AVR ............................................................................................................................. 14
1.7.1 Device architecture ....................................................................................................... 14
1.7.2 Program memory .......................................................................................................... 15
1.7.3 Internal data memory ................................................................................................... 15
1.7.4 Internal registers ........................................................................................................... 15
1.7.5 Program execution ........................................................................................................ 15
Chapter 2 - Introduction to Atmega128A Microcontroller .............................................................. 16
2.1 Features ................................................................................................................................ 16
2.2 Pin Configuration .................................................................................................................. 17
2.3 Block Diagram ....................................................................................................................... 18
2.4 Block Diagram of the AVR Architecture ................................................................................ 19
2.5 Program Memory Map ......................................................................................................... 20
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
P a g e | ii
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
P a g e | iii
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
P a g e | iv
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
Page |v
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
1| Introduction to Embedded Electronics
An embedded system is a computer system designed to do one or a few dedicated and/or specific
functions often with real-time computing constraints. It is embedded as part of a complete device
often including hardware and mechanical parts. By contrast, a general-purpose computer, such as a
personal computer (PC), is designed to be flexible and to meet a wide range of end-user needs.
Embedded systems control many devices in common use today.
In general, "embedded system" is not a strictly definable term, as most systems have some element
of extensibility or programmability. For example, handheld computers share some elements with
embedded systems such as the operating systems and microprocessors that power them, but they
allow different applications to be loaded and peripherals to be connected. Moreover, even systems
that do not expose programmability as a primary feature generally need to support software
updates. On a continuum from "general purpose" to "embedded", large application systems will
have subcomponents at most points even if the system as a whole is "designed to perform one or a
few dedicated functions", and is thus appropriate to call "embedded".
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
2| Introduction to Embedded Electronics
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.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
3| Introduction to Embedded Electronics
1.1.2 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.
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, I²C, 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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
4| Introduction to Embedded Electronics
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, TLCS-
47, 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
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
5| Introduction to Embedded Electronics
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.
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
6| Introduction to Embedded Electronics
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
7| Introduction to Embedded Electronics
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).
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
8| Introduction to Embedded Electronics
Example:
An instruction "Read a data byte from memory and store it in the accumulator" is executed as
follows: -
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
9| Introduction to Embedded Electronics
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
10| Introduction to Embedded Electronics
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
11| Introduction to Embedded Electronics
Processor stacks store/save the data in a simple way during program execution. Processor stack is a
part of RAM area where the data is saved in a Last In First Out (LIFO) fashion just like a stack of paper
on a table. Data is stored by executing a ‘push' instruction and data is read out using a ‘pop'
instruction.
I/O Registers: In addition to the Data memory, some special purpose registers are required that are
used in input/output and control operations. These registers are called I/O registers. These are
important for microcontroller peripheral interface and control applications.
As we already know a microcontroller has some embedded peripherals and I/O devices. The data
transfer to these devices takes place through I/O registers. In a microprocessor, input /output (I/O)
devices are externally interfaced and are mapped either to memory address (memory mapped I/O)
or a separate I/O address space (I/O mapped I/O).
These are the following options available for I/O register space in Harvard Architecture.
The first option is somewhat difficult to implement as there is no means to write to program ROM
area. It is also complicated to have a separate I/O space as shown in (3). Hence the second option
where I/O registers are placed in the register space is widely used.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
12| Introduction to Embedded Electronics
A 1960s architect who took the CISC (Complex Instruction Set Computer) approach was an architect
who could build a computing system that would utilize the smallest amount of assembly code
possible. Armed with fresh innovation in a world of growing technological advancement at his
disposal, and the Modus operandi of reducing the level of code, a CISC architect would strive to build
as much of the "coding" as possible into the computer’s hardware itself. An "Intelligent" and
"logical" processor hardware system which could "understand" high-level instructions would have
huge cost-cutting implications by enabling the use of minimal lines of code to achieve maximum
computer functionality and complete any computing task.
A CISC system would contain a Microprocessor instruction set so that each single instruction can
execute several low-level operations such as a load from memory, an arithmetic operation, and a
memory store, all in a single instruction. For a specific task, a CISC processor would come prepared
with a specific instruction, e.g. “ADD”.
Take a look at a working example to see how powerful and economical this system was:
ADD 2:3
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.
The RISC-brigade strive for an instruction set reduced both in size and complexity of addressing
modes which they argue enables easier implementation, greater instruction level parallelism, and
more efficient compilers. A RISC architect tries to keep the instruction set as simple as
possible so that a job can be executed within one clock cycle. Because all of the instructions execute
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
13| Introduction to Embedded Electronics
in a uniform amount of time (i.e. one clock), pipelining is possible. Rather than using an "intelligent"
hard-coded CPU hardware system, there is more emphasis on the software. Every slight small
hardware job can be managed and customized by the software used.
– LOAD A, 2:3
– LOAD B, 5:2
– ADD A, B
– STORE 2:3, A
They support only register-to-register operations and a few simple addressing modes. In using three
instructions codes to achieve only one task, larger amounts of RAM would be needed to store the
assembly code, and the compiler would need to do more work to convert that code to a lower-level
form. However, this is balanced by the more economical use of registers by means of a set of
"reduced instructions" which incorporate a reduced amount of transistors; and as already
mentioned, by maximizing the number of instructions per program, the number of clock cycles per
second is reduced. So, by using a number of small instructions rather than one "large" instruction,
the amount of actual work done by the machine is reduced.
If there were any advantages in this system, the RISC people certainly had their work cut-out for
them at first. RISC chips weren't in wide-circulation until the 1970s. Much of the software available
at the time was designed for CISC machines. It would have been a commercial risk to actually start
mass-producing this technology.
In the early years, there appeared more of a distinction between the two designs than appears
today. Systems designed on the RISC philosophy included IBM's System/360 (1964) which was the
first commercially available micro programmed computer architecture latter to become known as
CISC architecture. The success of System/360 resulted in CISC architectures dominating computer,
and later microprocessor, design for two decades. Other CISC computers included VAX (mid-1970s);
PDP-11 (1970s); and the Motorola 68000 series (1970s). CISC was also an influence on the Windows
3.1 (1992) and Windows 95 were designed with CISC processors in mind. If pure CISC design is not
commonly used in today’s computing systems, it may have to do with the following:
– 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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
14| Introduction to Embedded Electronics
Whatever the disadvantages in CISC usage, it took at least 10 years for RISC to take commercial
hold as Intel was one roadblock to its widespread implementation as Intel (a CISC user) had vast
resources to continue implementing the CISC model.
Although RISC is often thought of as a more recent development, in fact the first system which could
now be considered as RISC-based was the CDC 6600 supercomputer, designed in 1964. But the first
major RISC projects came from IBM, Stanford, and UC-Berkeley in the late 70s and early 80s. More
modern systems were Apple's Power Macintosh line (1994) Windows NT (1993) was RISC
compatible.
Nowadays, CISC and RISC conflict has ended with some factions claiming that RISC has won, and
have more or less converge. Examples of convergences include:
– 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.
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
15| Introduction to Embedded Electronics
The size of the program memory is usually indicated in the naming of the device itself (e.g., the
ATmega64x line has 64 kB of flash while the ATmega32x line has 32 kB).
In most variants of the AVR architecture, the working registers are mapped in as the first 32 memory
addresses (000016-001F16) followed by the 64 I/O registers (002016-005F16).
Actual SRAM starts after these register sections (address 006016). (Note that the I/O register space
may be larger on some more extensive devices, in which case the memory mapped I/O registers will
occupy a portion of the SRAM address space.)
Even though there are separate addressing schemes and optimized opcodes for register file and I/O
register access, all can still be addressed and manipulated as if they were in SRAM.
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.
The AVR family of processors were designed with the efficient execution of compiled C code in mind
and has several built-in pointers for the task.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
16| Introduction to Atmega128A Microcontroller
2.1 Features
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
17| Introduction to Atmega128A Microcontroller
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
18| Introduction to Atmega128A Microcontroller
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
19| Introduction to Atmega128A Microcontroller
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
20| Introduction to Atmega128A Microcontroller
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
21| Introduction to Atmega128A Microcontroller
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
22| JTAG Description and Installing FTDI Driver
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
23| JTAG Description and Installing FTDI Driver
http://www.ftdichip.com/Drivers/VCP.htm
2. Plug the USB cable (JTAG / USB on the board). Open Device Manager where you can see
following,
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
24| JTAG Description and Installing FTDI Driver
3. Right click on USB Serial Port and click on Update Driver Software
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
25| JTAG Description and Installing FTDI Driver
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
26| JTAG Description and Installing FTDI Driver
9. Now open Port Settings Tab and click on Advanced and choose desired COM Port and click on OK
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
27| WiNet (Wireless-Networking) Board Description
4.1 Peripherals
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
28| WiNet (Wireless-Networking) Board Description
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
29| WiNet (Wireless-Networking) Board Description
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
30| WiNet (Wireless-Networking) Board Description
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.
3.3V Regulator
Connect the 9V DC adapter provided, and press the DC-Jack Switch, RED power LED should turn ON,
indicating successful powering of the board.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
31| WiNet (Wireless-Networking) Board Description
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.
WiNet provides a USB interface for serial communication test applications. This USB interface is
actually an UART- USB interface based on FTDI232 chip for PC to WiNet communication. The
interface is as shown in figure below.
For installing drivers, please read the chapter ‘How to install FTDI Drivers’
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
32| WiNet (Wireless-Networking) Board Description
FTDI-232 ATmega128L
Microcontroller
JP5 JP6
TXD1 RXD1
1 1
2 TXD FTDI 2 RXD FTDI
2 2
CC2500 is a 2.4 GHz compliant radio. It has a data rate of 250Kbps and range of 30m (indoor) and
100m (outdoor). It is interfaced with the microcontroller via UART0.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
33| WiNet (Wireless-Networking) Board Description
TMP275 is a temperature sensor from TI. It has a resolution of 0.5 degree centigrade. It is a digital
output sensor interfaced with microcontroller via I2C. Details of TMP275 can be found in the
datasheet.
ATmega128A
TMP-275
Microcontroller VCC
SDA V+
VCC I2C_SDA
SCL A0
I2C_SCL
ALERT A1
INT6
GND
GND A2
Light sensor is APDS-9300 from Avago Technologies. The APDS-9300 is a low-voltage Digital Ambient
Light Photo Sensor that converts light intensity to digital signal output capable of direct I2C
interface. Each device consists of one broadband photodiode (visible plus infrared) and one infrared
photodiode. Details can be found in the Datasheet.
VCC
ATmega128A
APDS-9300
Microcontroller
ADDR_SEL
VSS
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
34| WiNet (Wireless-Networking) Board Description
WiNet board is connected to Ethernet via ENC28J60 chip from Microchip. It is an IEEE 802.3
compatible Ethernet controller with Integrated MAC and 10BASE-T PHY. TCP/IP stack reside on the
Atmega128A microcontroller and drives the ENC chip via SPI interface.
Install FTDI Drivers, Please read ‘How to Install FTDI Drivers’ chapter.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
35| WiNet (Wireless-Networking) Board Description
1. Connect the USB cable of the JTAG ICE to the computer. Install
the FTDI driver if it was not previously installed. See the FTDI driver
doc.
3. Check the COM PORT number is < 5. If not change it, see the
FTDI driver chapter for the same.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
36| Embedded Development Tools
A compiler which is used to compile code for platform other than the one you are using for
compilation. As we are compiling code for AVR microcontrollers on x86/x64 based PCs, we are using
cross-compilers. A cross-compiler is used when the host machine is not capable to compile the code
itself. Generally we use cross-compilers for Microcontroller code compilation.
Here, we will be using GNU based GCC compiler for AVR. For windows, the compiler is available as
WinAVR. WinAVR is windows version of AVR-GCC. The steps used for compilation with WinAVR are
exactly similar with avr-gcc.
In this chapter, we will be providing an overview of all the utilities required in the building process.
For further information on any command, please refer to man pages through linux. Also, you can
read the documentation online at: http://linux.die.net/man/.
1. avr-gcc => The compiler for AVR microcontrollers, which gives object code as output.
2. avr-as => AVR assembler, used for converting assembly code to object code.
3. avr-ld => AVR-GCC linker, which will combine all object files into executable file, ELF.
4. 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.
The installation procedure for avr-gcc is quite simple for both Linux as well as Windows.
For Linux(Ubuntu)
sudo apt-get install gcc-avr avrdude gdb-avr avr-libc binutils-avr avarice
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
37| Embedded Development Tools
As we know, we have a series of steps for building the executable code. The steps needed for
converting the source code to the intel based hex file, are as:
Linker: Translator/Copier:
Compiler:
Links the various Converts the
Compiles the
object files together to output binary into
source code to
form the binary the intel based hex
object code
output file (.out) file.
.c .o
.o .out .out .hex
main.c
#include<avr/io.h>
int main() {
DDRA = 0xff;
PORTA = 0x00;
return 0;
}
Here, we get main.o as output. By default, avr-gcc command performs Linking operation
automatically. We are using –c option to not to run linker but only perform compile action. This is
just to demonstrate the Linking Process separately.
Step 2: Linking
avr-gcc -mmcu=atmega128 main.o -o main.out
The resulting file after linking is main.out. The –o option is used to specify the output file. Please
note that using avr-gcc for linking is preferable.
We have final output in our hands as main.hex. We can program the MCU with it. We can also use
this program under any AVR Simulator. Programming the microcontroller is discussed later in this
chapter.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
38| Embedded Development Tools
Following is the command to use AVRDude program the Atmega-128 microcontroller connected via
JTAG programmer on COM Port 4.
CC=avr-gcc
This Macro is telling that we are using avr-gcc for compilation. Macros in makefile are quite similar
to Macros in C.
Once defined, we can use the Macro by appending a “$” sign with the Macro name enclosed in
brackets.
One major advantage of using Macros is that, if we need to change some setting, we can simply
change the Macro value. Rest of the program remains the same.
As we manually compiled the main.c earlier, now we can combine those steps under a label.
main:
avr-gcc main.c -mmcu=atmega128 -c
avr-gcc -mmcu=atmega128 main.o
avr-objcopy -O ihex a.out main.hex
makefile
#Makefile to compile main.c
CC=avr-gcc
LD=avr-gcc
MCU=atmega128
CFLAGS=-Wall -c
SRC=main.c
OUT=main.hex
PORT=com4
main:
$(CC) -mmcu=$(MCU) $(CFLAGS) $(SRC)
$(LD) -mmcu=$(MCU) *.o
avr-objcopy -O ihex a.out $(OUT)
program:
avrdude -p $(MCU) -P $(PORT) -c jtagmkI -U flash:w:$(OUT)
clean:
rm *.o *.hex *.out
The only difference here is that we are using Macros as explained earlier. Also, we have defined
multiple targets as main, program, clean.
make main
Make, by default is set to execute the very first label automatically. That is, the above command
could also have been written like:
make
If you wish to clean up the previously compiled files, we can issue a command:
make clean
This will result into removing all the object files and hex file.
This was just a brief introduction to make utility and makefiles. Please read the make documentation
for further help on make.
Makefile can be generated automatically using mFile utility. This utility is available within WinAVR.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
40| Embedded Development Tools
1. Editor => Used for writing the source code. Some good editors also provide Intellisense.
Intellisense is a feature which autocompletes the code as you type.
2. Toolchain => Toolchain is complete set of utilities required for compiling, linking, creating
hex file etc.
3. Debugger => Debugger is also built-in with the IDE.
4. Other Utilities => Some other supporting utilities are also available which help in speeding
up the development process.
In this section, we will be working on the standard IDE provided by Atmel, AVR Studio. We will learn
how we can create a Project, how to build, program and debug the microcontroller.
AVR Studio is used by embedded programmers for programming and debugging for many of the
Atmel microprocessors such as the Atmega8 or even the Atmega128. While it has support for
assembly programming for those who prefer to use higher languages, it uses the coff format for
debugging. Beginning with version 4 AVR Studio has now moved to dwarf2, and can be more readily
used in conjunction with the open source gcc based compiler WinAVR.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
41| Embedded Development Tools
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
42| Embedded Development Tools
3. Choose AVR-GCC and give path for project and type Project name. Click on Next.
4. Choose Debug Platform: JTAG ICE, Device: Atmega128, Port as per your system.
You can check platform options. Click on Finish.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
43| Embedded Development Tools
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
44| Embedded Development Tools
2. Select Platform as: JTAG ICE, select correct COM Port (you can also choose Auto) and click on
Connect. (Make sure Board’s power is ON and JTAG cable is connected in the correct orientation)
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
45| Embedded Development Tools
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
46| Embedded Development Tools
6. To burn a .hex file, go to Program, browse the file and click on Program.
10. To know more details and about JTAG debugging steps, please follow Atmel’s JTAG ICE manual,
www.atmel.com/atmel/acrobat/doc2475.pdf
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
47| 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. MACRO definitions
2. Typedef Keyword
3. Bit-Wise operators
4. Pointers
MACROs are constants which can be used to name an expression/statement. Whenever a MACRO is
called, it gets expanded to its original definition. MACRO processing is done by a Program called
Preprocessor. The process of preprocessing is done before compilation.
MACRO demo
#define PI 3.14
#define ADD(X,Y) (X)+(Y);
int main() {
printf(“%f”,PI); // Using PI macro
int result = ADD(5,6); // 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.
Typedef keyword is used to create new data types from existing data types. As an example, we can
use it to create a new data type uint_demo, which will work as unsigned int.
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
48| Embedded C Review
Bitwise operators can be used to directly manipulate the bits of int/char data-types. C provides us a
variety of such operators which are shown as:
Binary operators require 2 operands to work, while unary operator requires only 1 operand to
operate.
The AND, OR, XOR operations work according to following Truth tables.
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.
The values of x,y,z variables can be shown in the form of table as:
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
49| Embedded C Review
Here, the bits of variable a are shifted leftwards 2 times. The result can be illustrated as:
The Bit number 6 now becomes at Bit number 8 and hence, is removed due to overflow. Similarly
every other bit is shifted leftwards two times.
Here, the bit number 6 now becomes the 5th and similarly all other bits are shifted in right direction.
Hence, the right shift operation results in 24 as output.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
50| Embedded C Review
REGA |= 1 << x;
That will clear bit x of REGA. You must invert the bit string with the bitwise NOT operator (~),
then AND it.
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; // An char pointer
*ptr = &x; // The operator address-of(&) is used to retrieve address of variable x
char out = *ptr; // retrieves the value pointed by ptr
printf(“%d”,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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
51| Embedded C Review
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.
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
52| GPIO (General Purpose Input Output)
So let’s 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.
First of all we need to set whether we want a pin to act as output or input. DDRX register sets this.
Every bit corresponds to one pin of PORTX. Let’s have a look on DDRA register.
Bit 7 6 5 4 3 2 1 0
PIN PA7 PA6 PA5 PA4 PA3 PA2 PA1 PA0
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
53| GPIO (General Purpose Input Output)
Now to make a pin act as I/O we set its corresponding bit in its DDR register.
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 let’s take another example. Consider I want to set the pins of PORTB as shown in table,
For this configuration we have to set DDRB as 11010001 which in hexadecimal isD1. So we will write
DDRB=0xD1
Summary
This register sets the value to the corresponding PORT. Now a pin can be Output or Input. So let’s
discuss both the cases.
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.
Let’s 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.
For this configuration we have to set PORTA as 11000110 which in hexadecimal isC6. So we will
write PORTA=0xC6;
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
54| GPIO (General Purpose Input Output)
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
This register is used to read the value of a PORT. If a pin is set as input then corresponding bit on PIN
register is,
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
Use Right and Left Shift operators with binary Bit operators for setting, clearing, toggling, and
reading any particular bit of a register.
For Example, Clearing 5th bit of DDRC register can be done in following way,
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
55| 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.
They come in various types. The most popular one is 16x2 LCD module. It has 2 rows & 16 columns.
a) Text Display
b) Graphics Display
Text display can display all character set and graphics display can show any graphics because they
are interfaced pixel wise.
In recent year the LCD is finding widespread use replacing LEDs (seven segment LEDs or multi-
segment LEDs).
b) The ability to display the numbers, characters and graphics. This is not possible in LEDs, which can
display the numbers and few characters.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
56| 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:
It is theData
brain of LCD display. This
Register is handling
Command the all working ofBusy
Register the LCD.
flag
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
57| 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
LCD’s internal registers.
LCD Connections
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
58| LCD Interfacing
We will be using Peter Fleury’s libraries for the programming of LCD functions. The required files for
UART are lcd.c, lcd.h. The functions available in these files are described as:
#2 void lcd_clrscr(void);
Info Clear display and set cursor to home position.
#3 void lcd_home(void);
Info Set cursor to home position.
Change LCD_PORT if you want to use a different port for the LCD pins.
The four LCD data lines and the three control lines RS, RW, E can be on the same port or on different
ports. Change LCD_RS_PORT, LCD_RW_PORT, LCD_E_PORT if you want the control lines on different
ports.
Normally the four data lines should be mapped on one port, but it is possible to connect these data
lines in different order or even on different ports by adapting the LCD_DATAx_PORT and
LCD_DATAx_PIN definitions.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
59| LCD Interfacing
#define LCD_LINES 2
#define LCD_DISP_LENGTH 16
#define LCD_LINE_LENGTH 0x40
#define LCD_START_LINE1 0x00
#define LCD_START_LINE2 0x40
#define LCD_START_LINE3 0x14
#define LCD_START_LINE4 0x54
#define LCD_WRAP_LINES 0
#define LCD_IO_MODE 1
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
60| Accessing internal EEPROM
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.
The AVRLibC, included with WinAVR, contains prebuilt library routines for EEPROM access and
manipulation. Before we can make use of those routines, we need to include the eeprom library
header:
#include <avr/eeprom.h>
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:
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
61| UART Communication
Figure illustrates a basic UART data packet. While no data is being transmitted, logic 1 must be
placed in the Tx line. A data packet is composed of 1 start bit, which is always a logic 0, followed by a
programmable number of data bits (typically between 6 to 8), an optional parity bit, and a
programmable number of stop bits (typically 1). The stop bit must always be logic 1.
Most UART uses 8bits for data, no parity and 1 stop bit. Thus, it takes 10 bits to transmit a
byte of data.
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 UART’s baud rate
(and conversely the transmitter needs to know the receiver’s 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 receiver’s internal clock is set to the same frequency (though not the same phase). The receiver
"synchronizes" its internal clock to that of the transmitter’s at the beginning of every data packet
received. This allows the receiver to sample the data bit at the bit-cell center.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
62| UART Communication
A key concept in UART design is that UART’s 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 baud-
rate 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 transmitter’s 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 bit’s "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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
63| UART Communication
To communicate with the computer, you need a terminal where you can send data through
keyboard and the received data can be displayed on the screen. There are many softwares which
provide such terminal, but we will be using Docklight. Its evaluation version is free for download on
internet, which is sufficient for our purpose.
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
64| UART Communication
We will be using Peter Fleury’s libraries for the programming of UART protocol. The required files for
UART are uart.c, uart.h. The functions available in these files are described as:
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
65| SPI: Serial Peripheral Interface
11.1 Introduction
The Serial Peripheral Interface Bus or SPI bus is a synchronous serial data link used to communicate
between two or more microcontroller and devices supporting SPI mode data transfer. Devices
communicate in master/slave mode where the master device initiates the data frame. Multiple slave
devices are allowed with individual slave select (chip select) lines.
1. MOSI : Master Out Slave In (Tx for Master and Rx for Slave)
2. MISO : Master In Slave Out (Rx for Master Tx for Slave)
3. SCK : Serial Clock (Clock line)
4. SS : Slave Select (To select Slave chip) (if given 0 device acts as slave)
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
66| I2C Communication
12.1 Introduction
The I2C (Inter Integrated Circuit) Protocol is very popular for interfacing ICs with microcontroller
designed by Phillips. It uses only 2 bi-directional lines for communication with microcontroller. I2C is
a synchronous data transfer protocol & uses master/slave technique, where master (usually the
microcontroller) initiates the communication, while the slave (any I2C device) works according to
master. Multiple devices can connect at the same time, each having a unique 7-bit address. It can
allow up-to 128 devices on a single bus.
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
67| 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.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
68| 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.
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:
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:
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
69| I2C Communication
We will be using i2cmaster driver, which is Open Source and is fully compatible with At-Mega
Microcontrollers. It is purely written in assembly.
#1 void i2c_init(void);
Info Initialize the I2C master interface. Need to be called only once.
#2 void i2c_stop(void);
Info Terminates the data transfer and releases the I2C bus.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
70| Wireless Sensor Network (WSN)
A wireless sensor network (WSN) consists of spatially distributed autonomous sensors to monitor
physical or environmental conditions, such as temperature, sound, vibration, pressure, motion or
pollutants and to cooperatively pass their data through the network to a main location.
Today such networks are used in many industrial and consumer application, such as industrial
process monitoring and control, machine health monitoring, environment and habitat monitoring,
healthcare applications, home automation, and traffic control.
The WSN is built of "nodes" – from a few to several hundreds or even thousands, where each node is
connected to sensors.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
71| Wireless Sensor Network (WSN)
Sensor Node: Sensors like temperature, humidity, ambient light, motion, pressure etc.
Actuator Node: Actuators like LEDs, AC/Fan, Bulbs, Motors, HVAC, Alarm etc.
Gateway Node: Connects wireless sensor network to other world by converting data from wireless
to other protocol like USB, Ethernet, WiFi etc.
Sensor networks have been useful in a variety of domains. The primary domains at which sensor are
deployed follow:
Military monitoring. Military uses sensor networks for battlefield surveillance; sensors could
monitor vehicular traffic, track the position of the enemy or even safeguard the equipment of the
side deploying sensors.
Building monitoring. Sensors can also be used in large buildings or factories monitoring climate
changes. Thermostats and temperature sensor nodes are deployed all over the building’s area. In
addition, sensors could be used to monitor vibration that could damage the structure of a building.
Healthcare. Sensors can be used in biomedical applications to improve the quality of the provided
care. Sensors are implanted in the human body to monitor medical problems like cancer and help
patients maintain their health.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
72| Wireless Sensor Network (WSN)
Point-to-Point networks allow each node to communicate directly with another node without
needing to go through a centralized communications hub. Each Peer device is able to function as
both a “client” and a “server” to the other nodes on the network.
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
73| Wireless Sensor Network (WSN)
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
74| Wireless Sensor Network (WSN)
This High Speed CC2500 Based Wireless module is a plug and play replacement for the wired Serial
Port (UART) supporting baud rates upto 38400.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
75| Network Communication
OSI (Open Systems Interconnect) Model is a standardized approach which defines communication
between two or more devices communicating over some network. OSI provides a uniform way to
access networked resources.
OSI model is a logical model consisting of 7 layers. At sender’s side, each layer performs its
operation on the data, adds information using headers and sends it to the layer below it. At
receiver’s side, the same operations occur in reverse order. The layers get striped at receiver’s side.
Application Layer
Presentation Layer
Session Layer
Transport Layer
Network Layer
Data Link Layer
Physical Layer
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
76| 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 Interface Layer
Here Application Layer consists of Application Layer + Presentation Layer + Session Layer.
Also, Network Interface 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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
77| 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.
a. 0800 IP Datagram
b. 0806 ARP request/reply
c. 8035 RARP request/reply
4. Data=> Payload Data including all the Headers from layers above it.
5. CRC=> Cyclic Redundancy Check, attached as a Trailer, while all the other information is
attached in the form of Header Fields.
There is a maximum size of each data packet for the Ethernet protocol. This size is called the
maximum transmission unit (MTU). What this means is that sometimes packets may be broken up as
they are passed through networks with MTUs of various sizes.
A MAC address is a 48-bit address. It is generally represented in Hex notation. An example of a MAC
address is 00-17-C4-A3-76-69.
MAC address is also called Physical Address or Layer 2 Address. It is used to identify a machine
uniquely in a Local Network.
More information about the MAC addresses can be obtained from Wikipedia/Google.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
78| Network Communication
Application HTTP FTP Telnet Finger SSH DNS DNS SNMP RIP Ping
Layer POP3/IMAP SMTP Gopher BGP RADIUS
Time/NTP Whois TACACS+ SSL Traceroute tftp
Transport
Layer TCP UDP ICMP OSPF
Internet
Layer IP ARP
As you can easily guess, it is not possible to include all of the protocols available in this table. This
table contains a fairly limited set of the protocols. The dependency of each application layer protocol
is illustrated. As an example, HTTP protocol depends on TCP protocol, RADIUS protocol depends on
UDP protocol. Protocols like DNS in application layer can work with both TCP and UDP. Ping
command needs a special Transport Layer protocol called ICMP to work.
The Network Interface Layer is usually implemented in our Ethernet Hardware itself. With the TCP/IP
stack in hand, we have Transport and Network Layer implementation. The implementation of
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
79| Network Communication
various Application Layer protocols like HTTP, Telnet, Ping is discussed in later sections. Hence, we
have a complete implementation of all the layers. Once we have all the layers implemented, we
have a complete network application.
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.
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,
won’t 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.
1. SYN=> The active open is performed by the client sending a SYN to the server. It sets the
segment's sequence number to a random value A.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
80| Network Communication
2. SYN-ACK=> In response, the server replies with a SYN-ACK. The acknowledgment number is set
to one more than the received sequence number (A + 1), and the sequence number that the
server chooses for the packet is another random number, B.
3. ACK=> Finally, the client sends an ACK back to the server. The sequence number is set to the
received acknowledgement value i.e. A + 1, and the acknowledgement number is set to one
more than the received sequence number i.e. B + 1.
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.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
81| Network Communication
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.
1. Creation of packets
2. Routing of packets
3. Providing unique address to each and every device
14.3.3.1 IP Header
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
82| Network Communication
6. Type of Service=> type of service controls the priority of the packet. 0x00 is normal. The first
3 bits stand for routing priority, the next 4 bits for the type of service (delay, throughput,
reliability and cost).
7. Total Length=> Total length must contain the total length of the IP datagram. This includes
IP header and ICMP/UDP/TCP header and payload size in bytes.
8. Identification => the id sequence number is mainly used for reassembly of fragmented IP
datagrams. When sending single datagrams, each can have an arbitrary ID.
9. Fragment Offset, Flags=> The fragment offset is used for reassembly of fragmented
datagrams. The first 3 bits are the fragment flags, the first one always 0, the second the do-
not-fragment bit (set by ip_off |= 0x4000) and the third the more-flag or more-fragments-
following bit (ip_off |= 0x2000). The following 13 bits is the fragment offset, containing the
number of 8-byte big packets already sent.
10. Time to Live=> It is the amount of hops (routers to pass) before the packet is discarded, and
an icmp error message is returned. The maximum value of this field can be 255.
11. Protocol=> Transport layer protocol. can be tcp (6), udp(17), icmp(1), or whatever protocol
follows the IP header.
12. Checksum=> The datagram checksum for the whole ip datagram. every time anything in the
datagram changes, it needs to be recalculated, or the packet will be discarded by the next
router.
13. Source IP Address=> Source IP address, converted to long int format.
14. Destination IP Address=> Destination IP address, converted to long int format.
We can manually create and fill these headers to create and send a packet.
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.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
83| Network Communication
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.
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 1’s in Subnet Mask is called Network ID.
The part of IP Address, which is covered by 0’s of Subnet mask is Host ID. Based on the subnet mask,
we can categorize IP addresses into various classes.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
84| Network Communication
1. Taking an arbitrary message to be sent. This is the data to be sent by application layer.
2. Defining the TCP and IP headers as C structures.
3. Defining functions for checksum calculation, Converting IP address into 32-bit Integer format.
4. Filling up the values of header fields.
5. Sending the manually filled packet to Network Interface 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.
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
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
85| Network Communication
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.
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.
From the illustration, we can see that in addition to normal fields of ICMP headers, we can also add
some text/message in the packet. Here, Type=8 is Echo Request which is sent from the client side.
The server then replies the request with Type=0, Echo Reply. The detailed list of messages
supported by the ICMP protocol is available on the web.
Ping is a very useful utility, which can provide us some other diagnostic information also. It also
shows time server took to reply. You can try experimenting with the Ping command, exploring the
features it provides.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
86| Network Communication
HTTP is the underlying Application Layer protocol used to communicate on the Web. We can send
various requests using it and in return, we get some answer from Web Server.
GET / HTTP/1.1
User-Agent : Firefox
Host : www.google.com
In this case, User-Agent Firefox is requesting the default page (/) of Host www.google.com. The
request is made using HTTP Protocol version 1.1. Here User-Agent corresponds to the Brower used.
The GET method used above is one of various methods available in HTTP, some of which are:
1. GET – Used to request some information from a Server
2. HEAD – Similar to GET, but returns only Headers without any data
3. POST – Used to submit form data on the server
4. PUT – Used to upload a file on server
5. DELETE – Deletes a file from the Server
The general form of the request can be shown as:
In addition to that, some other information can be attached in the form of Headers.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
87| Network Communication
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.
Most Important Codes that we need to implement in our Web Server are:
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
88| 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.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
89| 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.
1. Network – A network is defined as group of two or more devices communicating with each
other.
2. Host/Network Device – A device which has ability to talk to other devices on a network.
Say, Computer, Mobile, Router etc.
3. NIC (Network Interface Card) – A hardware which enables a device to communicate over
the network.
4. Protocol – Set of Rules that govern some Operation. In simple words, Protocols describe the
way communication occurs between sender and receiver at various levels.
5. IP Address – A unique number that identifies a network device. It is a 32-bit Address and is
unique globally in case of internet.
6. Port number – A port number is a simple 16-bit integer value, which uniquely identifies an
application.
7. MAC Address – A 48-bit value which uniquely identifies a network device on a Local Area
Network.
8. HTTP – Hyper Text Transfer Protocol, is a protocol which defines method of communication
between a web client and web server.
9. PING – Packet INternet Groper, is a network command, which is used to check if a host is
alive or dead. This command works at Network Layer.
10. ARP – Address Resolution Protocol, is used for getting MAC address of a device if we know
the IP address. In other words, it resolves IP address to MAC address.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
90| Tux-Graphics TCP/IP Stack
15.1 Introduction
As we have discussed briefly about the TCP/IP stacks. Now, it is the time to actually build up an
Application using the stack. But, before building any application, we will be briefly discussing about
the Stack we will be using.
TuxGraphics.org provides an Open Source stack which can be used freely. In this section, we will be
briefly discussing the functions provided in the stack.
Filename Description
ip_arp_udp_tcp.(c|h) These files contain the TCP/IP stack functions, forming the Network,
Transport Layer.
enc28j60.(c|h) These files implement the Data Link Layer. Also, it contains functions to
communicate with ENC28J60 using SPI protocol. Basically, it is a driver to
communicate with ENC28J60.
net.h This contains some constant values of various header fields of TCP, IP,
Ethernet headers.
avr_compat.h Compatibility File used if you are using older version of AVR. It contains
some definitions which are used in thee Stack definition.
timeout.h It also contains some compatibility file includes related to delay functions.
Representation of IP Address
uint8_t myip[6] = {10,0,0,50};
Here, myip is the array of four 8-bit unsigned integers (uint8_t).
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
91| Tux-Graphics TCP/IP Stack
#7 uint16_t get_tcp_data_pointer(void);
Info This function returns the address of TCP packet in the stack buffer as an integer.
This function takes no arguments.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
92| Tux-Graphics TCP/IP Stack
ENC28J60 functions
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 | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
93| Appendix
Chapter 16 - Appendix
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
94| Appendix
A long time ago, in a very remote island known as Lilliput, society was split into two factions: Big-
Endians who opened their soft-boiled eggs at the larger end ("the primitive way") and Little-Endians
who broke their eggs at the smaller end. As the Emperor commanded all his subjects to break the
smaller end, this resulted in a civil war with dramatic consequences: 11.000 people have, at several
times, suffered death rather than submitting to breaking their eggs at the smaller end. Eventually,
the 'Little-Endian' vs. 'Big-Endian' feud carried over into the world of computing as well, where it
refers to the order in which bytes in multi-byte numbers should be stored, most-significant first (Big-
Endian) or least-significant first (Little-Endian) to be more precise.
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
The Intel x86 family and Digital Equipment Corporation architectures (PDP-11, VAX, Alpha) are
representatives of Little-Endian, while the Sun SPARC, IBM 360/370, and Motorola 68000 and 88000
architectures are Big-Endians. Still, other architectures such as PowerPC, MIPS, and Intel’s 64 IA-64
are Bi-Endian, i.e. they are capable of operating in either Big-Endian or Little-Endian mode.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
95| Appendix
The range gate's prediction of where the Scud will next appear is a function of the Scud's known
velocity and the time of the last radar detection. Velocity is a real number that can be expressed as a
whole number and a decimal (e.g., 3750.2563...miles per hour). Time is kept continuously by the
system's internal clock in tenths of seconds but is expressed as an integer or whole number (e.g., 32,
33, 34...). The longer the system has been running, the larger the number representing time. To
predict where the Scud will next appear, both time and velocity must be expressed as real numbers.
Because of the way the Patriot computer performs its calculations and the fact that its registers are
only 24 bits long, the conversion of time from an integer to a real number cannot be any more
precise than 24 bits. This conversion results in a loss of precision causing a less accurate time
calculation. The effect of this inaccuracy on the range gate's calculation is directly proportional to the
target's velocity and the length of the the system has been running. Consequently, performing the
conversion after the Patriot has been running continuously for extended periods causes the range
gate to shift away from the center of the target, making it less likely that the target, in this case a
Scud, will be successfully intercepted.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
96| Appendix
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.
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
97| Appendix
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
98| Appendix
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011
99| References
Chapter 17 - References
Advanced Embedded | Punit Narang | Manoj Gulati | Sourabh Sankule| June 2011