Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Programming in assembly language

Assembly language is a low-level programming language that provides a symbolic representation of machine language instructions, making it more understandable for software development. It offers advantages such as reduced memory usage and execution time, and is particularly suitable for hardware-specific tasks and time-critical jobs. The document also discusses the differences between compilers and assemblers, the structure of assembly programs, and the use of Embedded C in microcontroller applications.

Uploaded by

MARK SIMIYU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Programming in assembly language

Assembly language is a low-level programming language that provides a symbolic representation of machine language instructions, making it more understandable for software development. It offers advantages such as reduced memory usage and execution time, and is particularly suitable for hardware-specific tasks and time-critical jobs. The document also discusses the differences between compilers and assemblers, the structure of assembly programs, and the use of Embedded C in microcontroller applications.

Uploaded by

MARK SIMIYU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

https://www.tutorialspoint.com/assembly_programming/index.

htm

https://www.teachmint.com/tfile/studymaterial/class-
7th/embeddedsystems/iotlabmanualpdf/e5eb5434-e3f4-4316-80e0-ebc2fb326b90

What is Assembly Language?


Each personal computer has a microprocessor that manages the computer's arithmetical, logical, and
control activities.
Each family of processors has its own set of instructions for handling various operations such as getting
input from keyboard, displaying information on screen and performing various other jobs. These set of
instructions are called 'machine language instructions'.
A processor understands only machine language instructions, which are strings of 1's and 0's. However,
machine language is too obscure and complex for using in software development. So, the low-level
assembly language is designed for a specific family of processors that represents various instructions in
symbolic code and a more understandable form.
Advantages of Assembly Language
Having an understanding of assembly language makes one aware of −
 How programs interface with OS, processor, and BIOS;
 How data is represented in memory and other external devices;
 How the processor accesses and executes instruction;
 How instructions access and process data;
 How a program accesses external devices.
Other advantages of using assembly language are −
 It requires less memory and execution time;
 It allows hardware-specific complex jobs in an easier way;
 It is suitable for time-critical jobs;
 It is most suitable for writing interrupt service routines and other memory resident programs.
Basic Features of PC Hardware
The main internal hardware of a PC consists of processor, memory, and registers. Registers are
processor components that hold data and address. To execute a program, the system copies it from the
external device into the internal memory. The processor executes the program instructions.
The fundamental unit of computer storage is a bit; it could be ON (1) or OFF (0) and a group of 8
related bits makes a byte on most of the modern computers.
So, the parity bit is used to make the number of bits in a byte odd. If the parity is even, the system
assumes that there had been a parity error (though rare), which might have been caused due to hardware
fault or electrical disturbance.
The processor supports the following data sizes −
 Word: a 2-byte data item
 Doubleword: a 4-byte (32 bit) data item
 Quadword: an 8-byte (64 bit) data item
 Paragraph: a 16-byte (128 bit) area
 Kilobyte: 1024 bytes
 Megabyte: 1,048,576 bytes

Assembly language is dependent upon the instruction set and the architecture of the processor. In this
tutorial, we focus on Intel-32 processors like Pentium. To follow this tutorial, you will need
 An IBM PC or any equivalent compatible computer
 A copy of Linux operating system
 A copy of NASM assembler program
There are many good assembler programs, such as −
 Microsoft Assembler (MASM)
 Borland Turbo Assembler (TASM)
 The GNU assembler (GAS)
We will use the NASM assembler, as it is −
 Free. You can download it from various web sources.
 Well documented and you will get lots of information on net.
 Could be used on both Linux and Windows.
n assembly program can be divided into three sections −
 The data section,
 The bss section, and
 The text section.
The data Section
The data section is used for declaring initialized data or constants. This data does not change at
runtime. You can declare various constant values, file names, or buffer size, etc., in this section.
The syntax for declaring data section is −
section.data
The bss Section
The bss section is used for declaring variables. The syntax for declaring bss section is −
section.bss
The text section
The text section is used for keeping the actual code. This section must begin with the
declaration global _start, which tells the kernel where the program execution begins.
The syntax for declaring text section is −
section.text
global _start
_start:
Comments
Assembly language comment begins with a semicolon (;). It may contain any printable character
including blank. It can appear on a line by itself, like −
; This program displays a message on screen
or, on the same line along with an instruction, like −
add eax, ebx ; adds ebx to eax
Assembly Language Statements
Assembly language programs consist of three types of statements −
 Executable instructions or instructions,
 Assembler directives or pseudo-ops, and
 Macros.
The executable instructions or simply instructions tell the processor what to do. Each instruction
consists of an operation code (opcode). Each executable instruction generates one machine language
instruction.
The assembler directives or pseudo-ops tell the assembler about the various aspects of the assembly
process. These are non-executable and do not generate machine language instructions.
Macros are basically a text substitution mechanism.
Syntax of Assembly Language Statements
Assembly language statements are entered one statement per line. Each statement follows the following
format −
[label] mnemonic [operands] [;comment]
The fields in the square brackets are optional. A basic instruction has two parts, the first one is the
name of the instruction (or the mnemonic), which is to be executed, and the second are the operands or
the parameters of the command.
Following are some examples of typical assembly language statements −
INC COUNT ; Increment the memory variable COUNT

MOV TOTAL, 48 ; Transfer the value 48 in the


; memory variable TOTAL

ADD AH, BH ; Add the content of the


; BH register into the AH register

AND MASK1, 128 ; Perform AND operation on the


; variable MASK1 and 128

ADD MARKS, 10 ; Add 10 to the variable MARKS


MOV AL, 10 ; Transfer the value 10 to the AL register

Difference between Compiler and Assembler


Compiler:
A Compiler is primarily used for programs that translate source code from a high-level
programming language to a machine level language to create an executable program. A compiler
will consider the entire program as a whole code and then translates. The main job of the compiler is
that it checks all kinds of limits, ranges, errors, etc. Before the compiler can successfully execute the
code, the errors must be removed from the source code. Example of compiled languages is C, C++,
Java, C#, etc.

Assembler:
The Assembler takes as input the assembly code and translates it into relocatable machine code.
Assembler checks each instruction for its correctness and generates a diagnostic message, if

Difference between Compiler and Assembler:


Compiler Assembler
Compiler Assembler

Compiler converts the source code written by the Assembler converts the assembly
programmer to a machine level language. code into the machine code.

Assembler input assembly language


Compiler input source code. code.

But the Assembler can’t do this at


It converts the whole code into machine language at a time. once.

It takes less execution time compared to an assembler. It takes more time than a compiler.

It detects errors in the first phase,


It shows the whole program error after the whole program fixes them, and then the second
is scanned. phase is start to execute.

But, an Assembler is less intelligent


A Compiler is more intelligent than an Assembler. than a Compiler.

The compilation phases are lexical analyzer, syntax Assembler makes two phases over
analyzer, semantic analyzer, intermediate code generated, a the given input, first phase and the
code optimizer, code generator, and error handler second phase.

The output of compiler is a mnemonic version of machine The output of assembler is binary
code. code.

GAS, GNU is an example of an


C, C++, Java, and C# are examples of compiled languages. assembler.

Language Processors –
Compilers, interpreters, translate programs written in high-level languages into machine code that a
computer understands. And assemblers translate programs written in low-level or assembly language
into machine code. In the compilation process, there are several stages. To help programmers write
error-free code, tools are available.
Assembly language is machine-dependent, yet mnemonics used to represent instructions in it are not
directly understandable by machine and high-Level language is machine-independent. A computer
understands instructions in machine code, i.e. in the form of 0s and 1s. It is a tedious task to write a
computer program directly in machine code. The programs are written mostly in high-level
languages like Java, C++, Python etc. and are called source code. These source code cannot be
executed directly by the computer and must be converted into machine language to be executed.
Hence, a special translator system software is used to translate the program written in a high-level
language into machine code is called Language Processor and the program after translated into
machine code (object program/object code).
The language processors can be any of the following three types:
1. Compiler :
The language processor that reads the complete source program written in high-level language as a
whole in one go and translates it into an equivalent program in machine language is called
a Compiler. Example: C, C++, C#, Java.
In a compiler, the source code is translated to object code successfully if it is free of errors. The
compiler specifies the errors at the end of the compilation with line numbers when there are any
errors in the source code. The errors must be removed before the compiler can successfully
recompile the source code again
2. Assembler :
The Assembler is used to translate the program written in Assembly language into machine code.
The source program is an input of an assembler that contains assembly language instructions. The
output generated by the assembler is the object code or machine code understandable by the
computer. Assembler is basically the 1st interface that is able to communicate humans with the
machine. We need an Assembler to fill the gap between human and machine so that they can
communicate with each other. code written in assembly language is some sort of
mnemonics(instructions) like ADD, MUL, MUX, SUB, DIV, MOV and so on. and the assembler is
basically able to convert these mnemonics in Binary code. Here, these mnemonics also depend upon
the architecture of the machine.
For example, the architecture of intel 8085 and intel 8086 are different.

3. Interpreter :
The translation of a single statement of the source program into machine code is done by a language
processor and executes immediately before moving on to the next line is called an interpreter. If
there is an error in the statement, the interpreter terminates its translating process at that statement
and displays an error message. The interpreter moves on to the next line for execution only after the
removal of the error. An Interpreter directly executes instructions written in a programming or
scripting language without previously converting them to an object code or machine code.
Example: Perl, Python and Matlab.
8051 Embedded ‘C’ Programming
Definition:
An embedded system is an application that contains at least one programmable computer (typically in
the form of a microcontroller, a microprocessor or digital signal processor chip) and which is used by
individuals who are, in the main, unaware that the system is computer-based.

Introduction to Embedded C
Looking around, we find ourselves to be surrounded by various types of embedded systems. Be
it a digital camera or a mobile phone or a washing machine, all of them has some kind of processor
functioning inside it. Associated with each processor is the embedded software. If hardware forms the
body of an embedded system, embedded processor acts as the brain, and embedded software forms its
soul. It is the embedded software which primarily governs the functioning of embedded systems.
During infancy years of microprocessor based systems, programs were developed using assemblers and
fused into the EPROMs. There used to be no mechanism to find what the program was doing. LEDs,
switches, etc. were used to check correct execution of the program. Some ‘very fortunate’ developers
had In-circuit Simulators (ICEs), but they were too costly and were not quite reliable as well.
As time progressed, use of microprocessor-specific assembly-only as the programming
language reduced and embedded systems moved onto C as the embedded programming language of
choice. C is the most widely used programming language for embedded processors/controllers.
Assembly is also used but mainly to implement those portions of the code where very high timing
accuracy, code size efficiency, etc. are prime requirements.
Advantages of C:
Use of C in embedded systems is driven by following advantages. • It is small and reasonably simpler
to learn, understand, program and debug. C Compilers are available for almost all embedded devices in
use today, and there is a large pool of experienced C programmers. • Unlike assembly, C has advantage
of processor-independence and is not specific to any particular microprocessor/ microcontroller or any
system. This makes it convenient for a user to develop programs that can run on most of the systems. •
As C combines functionality of assembly language and features of high level languages, C is treated as
a ‘middle-level computer language’ or ‘high level assembly language’. C language is fairly efficient
and supports access to I/O and provides ease of management of large embedded projects. • Well proven
compilers are available for every embedded processor (8-bit to 32-bit). C x 51 Cross Compiler supports
all of the ANSI Standard C directives.

C Versus Embedded ‘C’


C Language Embedded ‘C’
‘C’ is a well structured, well defined and Embedded ‘C’ can be considered as a subset of
standardized general purpose programming ‘C’ language.
language.
‘C’ is used for desktop computers Embedded ‘C’ is for microcontroller based
applications
‘C’ has the luxury to use resources of a desktop Embedded ‘C’ has to use with the limited
PC like memory, OS, etc. on desktop systems resources (RAM, ROM, I/Os) on an embedded
processor
Compilers for ‘C’ (ANSI C) typically generate Embedded ‘C’ requires compilers (Cross
OS dependant executables Compilers) to create files to be downloaded to
the microcontrollers / microprocessors where it
needs to run

Embedded C Programs
1. An embedded C program to load a number into Accumulator.
# include<reg51.h>
void main( )
{
Acc = 0x25;
}
2. Write a program to load three numbers into Accumulator and send them to port 1
# include<reg51.h>
void main( )
{
Acc = 0x25;
P1 = Acc;
Acc = 0x46;
P1 = Acc;
Acc = 0x92;
P1 = Acc;
}

Embedded C Programs
 An embedded C program to load a number into Accumulator.
# include
void main( )
{
Acc = 0x25;
}

 Write a program to load three numbers into Accumulator and send them to port 1
# include
void main( )
{
Acc = 0x25;
P1 = Acc;
Acc = 0x46;
P1 = Acc;
Acc = 0x92;
P1 = Acc;
}

 Write an 8051 C program to send values 00 – FF to port P1.


#include
void main( )
{
unsigned char z;
for (z = 0; z <= 255; z++)
P1=z;
}

Timers of 8051
In Intel 8051, there are two 16-bit timer registers. These registers are known as Timer0 andTimer1.
The timer registers can be used in two modes. These modes areTimer mode and the Counter mode.
The only difference between these two modes is the source for incrementing the timer registers.

Timer Mode
In the timer mode, the internal machine cycles are counted. So this register is incremented in each
machine cycle. So when the clock frequency is 12MHz, then the timer register is incremented in each
millisecond. In this mode it ignores the external timer input pin.
Counter Mode
In the counter mode, the external events are counted. In this mode, the timer register is incremented for
each 1 to 0 transition of the external input pin. This type of transitions is treated as events. The external
input pins are sampled once in each machine cycle, and to determine the 1or 0 transitions, another
machine cycle will be needed. So in this mode, at least two machine cycles are needed. When the
frequency is12MHz, then the maximum count frequency will be 12MHz/24 = 500KHz. So for event
counting the time duration is 2 µs.
There are four different modes of the Timer or Counter. The Mode 0 to Mode 2 are for both of the
Timer/Counter. Mode 3 has a different meaning for each timer register. There is a register called
TMOD. This register can be programmed to configure these timers or counters.
The Serial port is used for serial communication in mode 1 and 3. Timer1 is used for generating the
baud rate. So only Timer0 is available for timer or counter operations.
TMOD Register
TMOD(Timer Mode) is an SFR. The address of this register is 89H. This is not bit-addressable.
Timer Timer1 Mode Timer0 Mode

Bit Details Gate (G) C/T M1 M0 Gate (G) C/T M1 M0


Now, let us see the circuit that controls the running of the timers.
In the following table, we will see the bit details and their different operations for high or low value.
Bit Details High Value(1) Low Value(0)

C/T Configure for the Counter operations Configure for the Timer operations

Gate (G) Timer0 or Timer1 will be in RunMode when Timer0 or Timer1 will be in RunMode when
TRX bit of TCON register is high. TRX bit of TCON register is high
and INT0 or INT1 is high.

Bit Details 00 01 10 11

M1 M0 This is for Mode 0. (8- This is Mode 1. This is Mode 3 (8- This is Mode 3 (The
bit timer/counter, with (16-bit bit auto reload- function depends on
5-bit pre-scaler) timer/counter) timer/counter) Timer0 or Timer1)
The Gate bit will be high when the timer or counter is in mode 0 to 2.
Examples
To configure the Timer0 as 16-bit event counter and Timer1 as 8-bit auto reload counter, we can use
the bit pattern 0 0 1 0 0 1 0 1. It is equivalent to 25H. If we want to program the TMOD register with
this bit pattern, we can use this instruction:
MOVTMOD, #25H
The above instruction is executed, then the timer/counter will be controlled by the software. To
configure the system as hardware controlled mode, then the gate bits will be 1. So the bit patterns will
be 1 0 1 0 1 1 0 1 = ADH
we can use this instruction:
MOVTMOD, #0ADH
Mode 0 of Timer/Counter
The Mode 0 operation is the 8-bit timer or counter with a 5-bit pre-scaler. So it is a 13-bit
timer/counter. It uses 5 bits of TL0 or TL1 and all of the 8-bits of TH0 or TH1.
In this example the Timer1is selected, in this case, every 32 (25)event for counter operations or 32
machine cycles for timer operation, the TH1 register will be incremented by 1. When the
TH1overflows from FFH to 00H, then the TF1 of TCON register will be high, and it stops the
timer/counter. So for an example, we can say that if the TH1 is holding F0H, and it is in timer mode,
then TF1will be high after 10H * 32 = 512 machine cycles.
MOVTMOD, #00H
MOVTH1, #0F0H
MOVIE, #88H
SETB TR1
In the above program, the Timer1 is configured as timer mode 0. In this case Gate = 0. Then the TH1
will be loaded with F0H, then enable the Timer1 interrupt. At last set the TR1 of TCON register, and
start the timer.
Mode 1 of Timer/Counter
The Mode 1 operation is the 16-bit timer or counter. In the following diagram, we are using Mode 1
for Timer0.

In this case every event for counter operations or machine cycles for timer operation, the TH0– TL0
register-pair will be incremented by 1. When the register pair overflows from FFFFH to 0000H, then
the TF0 of TCON register will be high, and it stops the timer/counter. So for an example, we can say
that if the TH0 – TL0 register pair is holding FFF0H, and it is in timer mode, then TF0 will be high
after 10H = 16 machine cycles. When the clock frequency is 12MHz, then the following instructions
generate an interrupt 16 µs after Timer0 starts running.
MOVTMOD, #01H
MOVTL0, #0F0H
MOVTH0, #0FFH
MOVIE, #82H
SETB TR0
In the above program, the Timer0 is configured as timer mode 1. In this case Gate = 0. Then the TL0
will be loaded with F0H and TH0 is loaded with FFH, then enable the Timer0 interrupt. At last set the
TR0 of TCON register, and start the timer.
Mode 2 ofTimer/Counter
The Mode 2 operation is the 8-bit auto reload timer or counter. In the following diagram, we are using
Mode 2 for Timer1.
In this case every event for counter operations or machine cycles for timer operation, the TL1register
will be incremented by 1. When the register pair overflows from FFH to 00H, then the TF1 of TCON
register will be high, also theTL1 will be reloaded with the content of TH1 and starts the operation
again.
So for an example, we can say that if the TH1 and TL1 register both are holding F0H and it is in timer
mode, then TF1 will be high after 10H= 16 machine cycles. When the clock frequency is 12MHz this
happens after 16 µs, then the following instructions generate an interrupt once every 16 µs after
Timer1 starts running.
MOVTMOD, #20H
MOVTL1, #0F0H
MOVTH1, #0F0H
MOVIE, #88H
SETBTR1
In the above program, the Timer1 is configured as timer mode 2. In this case Gate = 0. Then the TL1
and TH1 are loaded with F0H. then enable the Timer1 interrupt. At last set the TR1 of TCON register,
and start the timer.
Timer1 in mode 2 generates the desired baud rate when the serial port is working on Mode 1 or 3.
Mode 3 of Timer/Counter
Mode 3 is different for Timer0 and Timer1. When the Timer0 is working in mode 3, the TL0 will be
used as an 8-bit timer/counter. It will be controlled by the standard Timer0 control bits, T0
and INT0 inputs. The TH0 is used as an 8-bit timer but not the counter. This is controlled by Timer1
Control bit TR1. When the TH0 overflows from FFH to 00H, then TF1 is set to 1. In the following
diagram, we can Timer0 in Mode 3.
When the Timer1 is working in Mode 3, it simply holds the count but does not run. When Timer0 is in
mode 3, the Timer1 is configured in one of the mode 0, 1 and 2. In this case, the Timer1 cannot
interrupt the microcontroller. When the TF1 is used by TH0 timer, the Timer1 is used as Baud Rate
Generator.
The meaning of gate bit in Timer0 and Timer1 for mode 3 is as follows
It controls the running of 8-bit timer/counter TL0 as like Mode 0, 1, or 2. The running of TH0 is
controlled by TR1 bit only. So the gate bit in this mode for Timer0 has no specific role.
The mode 3 is present for applications requiring an extra 8-bit timer/counter. In Mode 3 of Timer0,
the 8051 has three timers. One 8-bit timer by TH0, another8-bit timer/counter by TL0, and one 16-bit
timer/counter by Timer1.
If the Timer0 is in mode3, and Timer1 is working on either 0, 1 or 2, then the gun control of the
Timer1 is activated when the gate bit is low or INT1 is high. The run control is deactivated when the
gate is high and INT1 is lo

Serial Communication in 8051 Microcontroller

Serial Communication using 8051

Microcontrollers need to communicate with external devices such as sensors, computers and so on to
collect data for processing. Data communication is generally done by means of two methods – Parallel
and Serial mode. In parallel mode data bits are transferred faster using more data pins. But when comes
to a Microcontroller, we cannot afford to dedicate many pins for data transfer. UART or Serial
communication in 8051 microcontroller will allow the controller to send and receive data’s just by
using two pins
Serial Communication uses only two data pins to establish communication between Microcontroller
and external devices. In this mode of communication data is transferred one bit at a time. This article
describes Interfacing of 8051 with PC to establish communication through its serial port RS232.

RS232 AND MAX232:


To establish communication between a controller and PC, we must use serial I/O protocol RS-232
which was widely used in PC and several devices. PC works on RS-232 standards which operates at a
logic level of -25V to +25V. But Microcontrollers use TTL logic which works on 0-5V is not
compatible with the RS-232 voltage levels.
MAX232 is a specialized IC which offers intermediate link between the Microcontroller and PC. The
transmitter of this IC will convert the TTL input level to RS-232 Voltage standards. Meanwhile the
receiver of this IC will convert RS-232 input to 5V TTL logic levels. Read the complete working
of MAX232 IC.
SCON REGISTER:

SCON Register

It a bit addressable register used to set the mode in which serial communication takes place in the
controller. The above figure shows the configuration of the SCON register. Here is the list of functions
of each bit.

Serial Mode of 8051

SM0, SM1: Serial Mode control Bits


SM2: Multiprocessor mode control bit, logic 1 enables Multi processor mode and 0 for normal mode.
REN: Enables Serial reception. If set, it enables the reception otherwise the reception is disabled.
TB8: It is the 9th bit of the data that is to be transmitted.
RB8: It is used in modes 2 and 3, it is the 9th bit received by the microcontroller.
TI: It is known as Transmit Interrupt flag which is set by hardware to indicate the end of a
transmission. It has to be cleared by the software.
RI: It is known as Receive Interrupt flag which is set by hardware to indicate the end of a reception. It
has to be cleared by the software.
BAUD RATE:
It is defined as number of bits transmitted or received per second and usually expressed in Bits per
second bps. For mode 0 and mode 2 the baud rate is determined by means of 1/12, 1/32 or 1/64 of
crystal frequency whereas for mode 1 and 3 it is determined by means of timer 1.

Baud Rate by Timer1

Learn how to configure Timers in 8051.


SBUF REGISTER:
It is a 8 bit register that holds the data needed to be transmitted or the data that is received recently. The
serial port of 8051 is full duplex so the microcontroller can transmit and receive data using the register
simultaneously.
CODE:
#include<reg51.h>

void initialize() // Initialize Timer 1 for serial communication

TMOD=0x20; //Timer1, mode 2, baud rate 9600 bps

TH1=0XFD; //Baud rate 9600 bps

SCON=0x50;

TR1=1; //Start timer 1

void receive() //Function to receive serial data


{

unsigned char value;

while(RI==0); //wait till RI flag is set

value=SBUF;

P1=value;

RI=0; //Clear the RI flag

void transmit() // Funtion to transmit serial data

SBUF='o'; //Load 'o' in SBUF to transmit

while(TI==0); //Wait till TI flag is set or data transmission ends

TI=0; //Clear TI flag

SBUF='k';

while(TI==0);

TI=0;

void main()

while(1)

initialize();
receive();

transmit();

Initialize() – Initialize timer for baud rate and set mode for serial transmission. The above program will
receive a character from PC and in return transmits “ok” back to PC. This code have three parts
initialize() ,receive() and transmit() to perform the process of serial communication. This can be tested
using Hyperterminal software after connecting your controller to PC through RS232.
 Initialize() – Enables the Serial communication by configuring TMOD and SCON registers.
 Receive() – Check whether the microcontroller has received data from PC.
 Transmit() – Transmit bits ‘o’ and ‘k’ to form the message “ok” back to PC.

8051 I2C Interfacing

Before getting into I2C interfacing with 8051, Please read the below topics.

 I²C Basics
 I²C Advanced
 8051 -UART Interfacing
Introduction

I²C

I²C is a serial computer bus, which is invented by NXP semiconductors previously it is named as
Philips semiconductors. The I²C bus is used to attach low-speed peripheral integrated circuits to
microcontrollers and processors. I²C bus uses two bidirectional open-drain lines such as SDA (serial
data line) and SCl (serial clock line) and these are pulled up with resistors. I²C bus permits a master
device to start communication with a slave device. Data is interchanged between these two devices.
Typical voltages used are +3.3V or +5V although systems with extra voltages are allowed. Nowadays
new microcontrollers have inbuilt I²C Registers. But in 8051 there is no such registers. So we have to
achieve I²C in 8051

Many devices support I²C. For example, EEPROM, ADC, LCD, etc. For the sake of implementing I²C,
we are going to interface EEPROM.
EEPROM

Electrically Erasable Programmable ROM (EEPROM) is a user-modifiable ROM that can be removed
and reprogrammed frequently through the application of higher than the normal electrical voltage. An
EEPROM is a kind of non-volatile memory used in electronic devices like computers to store small
quantities of data that should be saved when power is detached.

Ad
Connection Diagram

SCK – P3.6

SDA – P3.7

I²C Implementation

Write Mode

1. Send the START command from the Master.


2. Send Device (EEPROM) Address with write mode.
3. Send Register address in Device (EEPROM), Where we have to access.
4. Send the Data to the Device (EEPROM).
5. If you want to send more than one byte, keep sending that byte.
6. Finally, Send the STOP command.
Read Mode

 Send the START command from the Master.


 Send Device (EEPROM) Address with write mode.
 Send Register address in Device (EEPROM), Where we have to access.
 Send again START command or Repeated START command.
 Send Device address with Reading mode.
 Read the data from Device (EEPROM).
 Finally, Send the STOP command.
Code

In our code, First, we will Write the Data into EEPROM. Then we will read that data from EEPROM
and send it to Serial Communication (UART). So it will print in the serial console.

START Command

Just go through the above diagram. In this

1. Initially, SDA and SCL are High.


2. SDA first goes to Zero.
3. Then SCL goes to Zero.
This is the START condition. Look at the below code

STOP Command

When SCL is High, We have to toggle the SDA Low to High.


Send Data

Sending Data and addresses are the same procedure. Here we have to send bit by bit to the SDA based
on the SCL.

Read Data

Reading also the same as write data. We have to read bit by bit from the SDA line based on SCL.

Serial Peripheral Interface(SPI)


The embedded system basically uses serial communication to communicate with the peripherals.
There are many serial communication protocols, such as UART, CAN, USB, I2C and SPI
communication. The serial communication protocol’s characteristics include high speed and low data
loss. It makes system-level designing easier, and ensures reliable data transfer.

Serial Data Communication


Electrically-coded information is called a serial data, which is transmitted bit by bit from one device to
another through a set of protocols. In the embedded system, control sensors and actuators data is
received or transmitted to the controller devices such as microcontrollers so that the data is further
analyzed and processed. As the microcontrollers work with the digital data, the information from
the analog sensors, actuators and other peripherals is converted into one byte (8-bit) binary word prior
to being transmitted to the microcontroller.

Serial Data Communication

This serial data is transmitted with respect to certain clock pulse. The data transmission rate is referred
to as the baud rate. The number of data bits that can be transmitted per second is called as baud rate.
Suppose the data is of 12 bytes, then each byte is converted into 8bits so that the total size of the data
transmission is about 96bits/sec of the data (12bytes*8 bits per byte). If the data can be transmitted
once every second, the baud rates are around 96bits/sec or 96 baud. The display screen refreshes the
data value once every second.

Serial Peripheral Interface Basics

The SPI communication stands for serial peripheral interface communication protocol, which was
developed by the Motorola in 1972. SPI interface is available on popular communication controllers
such as PIC, AVR, and ARM controller, etc. It has synchronous serial communication data link that
operates in full duplex, which means the data signals carry on both the directions simultaneously.
SPI protocol consists of four wires such as MISO, MOSI, CLK, SS used for master/slave
communication. The master is a microcontroller, and the slaves are other peripherals like sensors, GSM
modem and GPS modem, etc. The multiple slaves are interfaced to the master through a SPI serial bus.
The SPI protocol does not support the Multi-master communication and it is used for a short distance
within a circuit board.

Serial Peripheral Interface Basics

SPI Lines

MISO (Master in Slave out): The MISO line is configured as an input in a master device and as an
output in a slave device.

MOSI (Master out Slave in): The MOSI is a line configured as an output in a master device and as an
input in a slave device wherein it is used to synchronize the data movement.
SCK (serial clock): This signal is always driven by the master for synchronous data transfer between
the master and the slave. It is used to synchronize the data movement both in and out through the MOSI
and MISO lines.
SS (Slave Select) and CS (Chip Select): This signal is driven by the master to select individual
slaves/Peripheral devices. It is an input line used to select the slave devices.
Master Slave Communication with SPI Serial Bus

Single Master and Single Slave SPI Implementation

Here, the communication is always initiated by the master. The master device first configures the clock
frequency which is less than or equal to the maximum frequency that the slave device supports. The
master then selects the desired slave for communication by dragging the chip select line (SS) of that
particular slave device to go low state and active. The master generates the information on to the MOSI
line that carries the data from master to slave.
Master Slave Communication

Single Master and Multiple Slave Implementations

This is a multiple slave configuration with one master and multiple slaves through the SPI serial bus.
The multiple slaves are connected in parallel to the master device with the SPI serial bus. Here, all the
clock lines and data lines are connected together, but the chip select pin from each slave device must be
connected to a separate slave select pin on the maser device.

Single Master and multiple slaves

In this process, the control of each slave device is performed by a chip select line (SS). The chip select
pin goes low to activate the slave device and goes high to disable the slave device.

The data transfer is organized by using the shift registers at both master and slave devices with a given
word size of about 8-bit and 16-bit, respectively. Both the devices are connected in a ring form so that
the maser shift register value is transmitted through the MOSI line, and then the slave shifts data in its
shift register. The data is usually shifted out with the MSB first and shifting new LSB into the same
register.
Data Transfer between Master and Slave

Significance of Clock Polarity and Phase

Generally the transmission and reception of data is performed with respect to the clock pulses at rising
edges and falling edges. The Advanced microcontrollers have two frequencies: internal frequency and
external frequency. SPI peripherals could be added by sharing the MISO, MOSI and SCLK lines. The
peripherals are of different types or speeds like ADC, DAC, etc. So we need to change the SPCR
settings between the transfers to different peripherals.

SPCR register

The SPI bus operates in one of the 4 different transfer modes with a clock polarity (CPOL) and clock
phase (CPHA) which defines a clock format to be used. The clock polarity and the phase clock rates
depend on which peripheral device you are trying to communicate with the master.
CPHA=0, CPOL=0: The first bit starts as a lower signal – the data is sampled at rising edge and the
data changes on falling edge.

CPHA=0, CPOL=1: The first bit starts with a lower clock – the data is sampled at falling edge and the
data changes on rising edge.

CPHA=1, CPOL=0: The first bit starts with a higher clock – the data is sampled at falling edge and the
data changes on rising edge.

CPHA=1, CPOL=1: The first bit starts with a higher clock – the data is sampled at rising edge, and the
data changes on falling edge.
SPI Bus timings

SPI Communication Protocol

Many microcontrollers have inbuilt SPI protocols that handle all of the sending and receiving data. Any
of the data mode operations (R/W) is controlled by a control and status registers of the SPI Protocol.
Here, you can observe the EEPROM interface to the PIC16f877a microcontroller through the SPI
protocol.

Here, 25LC104 EEROM is a 131072 bytes memory wherein the microcontroller transfers two bytes of
data to the EEROM memory through a SPI serial bus. The program for this interfacing is given below.

Master to Slave communication through SPI serial bus

#include<pic16f877x.h>
Sbit SS=RC^2;
Sbit SCK=RC^3;
Sbit SDI=RC^4;
Sbit SDO=RC^5;
Void initialize EEROM();
Void main()
{
SSPSPAT=0x00;
SSPCON=0x31;
SMP=0;
SCK=0;
SDO=0;
SS=1;
EE_adress=0x00;
SPI_write( 0x80);
SPI_write(1234);
SS=0;
}

Advantages of SPI Protocol

 It is a full duplex communication.


 It is high-speed data bus 10MHzs.
 It is not limited to 8bits while transferring
 Hardware interfacing is simple through SPI.
 Slave uses a master clock and doesn’t need precious oscillators.
This is all about the SPI communications and its interfacing with a microcontroller.

Advantages of SPI:

 It's faster than asynchronous serial


 The receive hardware can be a simple shift register
 It supports multiple peripherals

Disadvantages of SPI:

 It requires more signal lines (wires) than other communications methods


 The communications must be well-defined in advance (you can't send random amounts of data
whenever you want)
 The controller must control all communications (peripherals can't talk directly to each other)
 It usually requires separate CS lines to each peripheral, which can be problematic if numerous
peripherals are needed.
Difference between can I2C and SPI?
I2C is half duplex communication and SPI is full duplex communication. I2C supports multi
master and multi slave and SPI supports single master. I2C is a two wire protocol and SPI is a four
wire protocol. I2C supports clock stretching and SPI does not have clock stretching.
Difference between can and I2C
CAN is a message based protocol. I2C is a address based protocol. In CAN each node can
behave as Master or Slave. *In I2C the slave device can't be a master.
CAN and SPI difference
The biggest difference between CAN and SPI is that the CAN protocol defines packets. In SPI
(and serial interfaces in general), only the transmission of a byte is fully defined. Given a mechanism
for byte transfer, software can provide a packet layer, but no standard size or type exists for a serial
packet.

Bluetooth Interfacing with 8051


Hardware Features
 Typical ‐80dBm sensitivity.
 Up to +4dBm RF transmit power.
 3.3 to 5 V I/O.
 PIO(Programmable Input/Output) control.
 UART interface with programmable baud rate.
 With integrated antenna.
 With edge connector.
Software Features
 Slave default Baud rate: 9600, Data bits:8, Stop bit:1,Parity:No parity.
 Auto‐connect to the last device on power as default.
 Permit pairing device to connect as default.
 Auto‐pairing PINCODE:”1234” as default.
Pin Description
The HC-05 Bluetooth Module has 6pins. They are as follows:

ENABLE:

When enable is pulled LOW, the module is disabled which means the module
will not turn on and it fails to communicate. When enable is left open or
connected to 3.3V, the module is enabled i.e the module remains
on and communication also takes place.

Vcc:

Supply Voltage 3.3V to 5V

GND:

Ground pin
TXD & RXD:

These two pins act as a UART interface for communication

STATE:

It acts as a status indicator. When the module is not connected to / paired with
any other Bluetooth device, the signal goes Low. At this low state, the led flashes
continuously which denotes that the module is not paired with another device.
When this module is connected to/paired with any other Bluetooth device, the
signal goes High. At this high state, the led blinks with a constant delay say for
example 2s delay which indicates that the module is paired.

BUTTON SWITCH:

This is used to switch the module into AT command mode. To enable AT command
mode, press the button switch for a second. With the help of AT commands, the
user can change the parameters of this module but only when the module is not
paired with any other BT device. If the module is connected to any other Bluetooth
device, it starts to communicate with that device and fails to work in AT command
mode.

Bluetooth Interfacing with 8051


Connection
Bluetooth Module

 Rx – P3.1 (TxD)
 Tx – P3.0 (RxD)
DC Motor (L293D Driver)

 In 1 – P2.0
 In 2 – P2.1
 En 1 – Vcc
 In 3 – P2.2
 In 4 – P2.3
 En 2 – Vcc
Source Code
The program given below is the HC-05 Bluetooth module interfacing with 8051.
This process is quite different from others since we are going to use android mobile
to control and communicate with 8051. Here the Bluetooth module acts as an
interface between our mobile and 8051 board. Before getting into the execution
process, follow the given procedure:

 First of all, the user should install an application called Bluetooth SPP
PRO from the play store which is a free application.
 After installation, pair the Bluetooth module to your mobile as like connecting
one device to another using Bluetooth. The default pairing code is 1234.
 Upload the given program to the 8051 board.
 The Bluetooth SPP PRO has three types of communication modes. Here
Byte stream mode is used to communicate. So select that mode and give the
input as below.
F – Forward

R – Reverse
L – Left

Ad
Ad
W – Right
 So We can control the motor using Mobile by Bluetooth. We can use this
setup for developing robots using Bluetooth.

You might also like