Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Chapter-8: Microcontrollers

1. What is Microcontroller?

Microcontroller:
The microcontroller is the electronic device. It has processing unit along with fixed sized ROM,
RAM, and other required peripheral components. These all the components are embedded on the
single chip. As it has all the components required to process and store data, it is also called
as minicomputer or computer on the single chip.
Below is the block diagram of the architecture of microcontroller.

Figure: Microcontroller on a single chip


It is widely used in embedded system.
2. What are the structural components of a microcontroller?

Figure: Structure of a microcontroller


Any electric appliance that stores, measures, displays information or calculates comprise of a
microcontroller chip inside it. The basic structure of a microcontroller comprise of:-
CPU – Microcontrollers brain is named as CPU. CPU is the device which is employed to fetch data,
decode it and at the end complete the assigned task successfully. With the help of CPU all the
components of microcontroller is connected into a single system. Instruction fetched by the
programmable memory is decoded by the CPU.
Memory – In a microcontroller memory chip works same as microprocessor. Memory chip stores
all programs & data. Microcontrollers are built with certain amount of ROM or RAM (EPROM,
EEPROM, etc.) or flash memory for the storage of program source codes.
Input/output ports – I/O ports are basically employed to interface or drive different appliances such
as- printers, LCD’s, LED’s, etc.
Serial Ports – These ports give serial interfaces amid microcontroller & various other peripherals
such as parallel port.
Timers – A microcontroller may be in-built with one or more timer or counters. The timers &
counters control all counting & timing operations within a microcontroller. Timers are employed to
count external pulses. The main operations performed by timers’ are- pulse generations, clock
functions, frequency measuring, modulations, making oscillations, etc.
ADC (Analog to digital converter) – ADC is employed to convert analog signals to digital ones.
The input signals need to be analog for ADC. The digital signal production can be employed for
different digital applications (such as- measurement gadgets).
Interpret Control- This controller is employed for giving delayed control for a working program.
The interpret can be internal or external.
Special Functioning Block – Some special microcontrollers manufactured for special appliances
like- space systems, robots, etc., comprise of this special function block. This special block has
additional ports so as to carry out some special operations.
3. Microcontroller Features:
Microcontrollers usually contain from several to dozens of general purpose input/output pins (GPIO).
GPIO pins are software configurable to either an input or an output state. When GPIO pins are
configured to an input state, they are often used to read sensors or external signals. Configured to the
output state, GPIO pins can drive external devices such as LEDs or motors, often indirectly, through
external power electronics.
Many embedded systems need to read sensors that produce analog signals. This is the purpose of
the analog-to-digital converter (ADC). Since processors are built to interpret and process digital data,
i.e. 1s and 0s, they are not able to do anything with the analog signals that may be sent to it by a
device. So the analog to digital converter is used to convert the incoming data into a form that the
processor can recognize. A less common feature on some microcontrollers is a digital-to-analog
converter (DAC) that allows the processor to output analog signals or voltage levels.
In addition to the converters, many embedded microprocessors include a variety of timers as well.
One of the most common types of timers is the programmable interval timer (PIT). A PIT may either
count down from some value to zero, or up to the capacity of the count register, overflowing to zero.
Once it reaches zero, it sends an interrupt to the processor indicating that it has finished counting.
This is useful for devices such as thermostats, which periodically test the temperature around them
to see if they need to turn the air conditioner on, the heater on, etc.
A dedicated pulse-width modulation (PWM) block makes it possible for the CPU to control power
converters, resistive loads, motors, etc., without using many CPU resources in tight timer loops.
A universal asynchronous receiver/transmitter (UART) block makes it possible to receive and
transmit data over a serial line with very little load on the CPU. Dedicated on-chip hardware also
often includes capabilities to communicate with other devices (chips) in digital formats such as Inter-
Integrated Circuit (I²C), Serial Peripheral Interface (SPI), Universal Serial Bus (USB), and Ethernet.
4. Types of microcontroller
Microcontroller can be categorized on the basis of architecture and service providers.
On the basis of architecture the types of microcontroller are:
1. Harvard Architecture
2. Von Neumann Architecture
On the basis of Service Provider or Vendor the types of microcontroller are:
1. AVR
2. PIC
3. Hitachi
4. Motorola
Types of Microcontroller on the basis of Architecture

On the basis of architecture the types of microcontroller are:

1) Havard Architecture: In Havard architecture separate storage and signal buses are provided for different set
of instructions and data. This architecture has the entire data storage within the CPU and there is no access
available for instruction storage as data.
This architecture provides simultaneous access to an instructions and data stored inside internal buses of
microcontroller.
Let's see the block diagram of Havard Architecture:

2) Von Neumann Architecture: This architecture of microcontroller was proposed by scientist John Von
Neumann. In this architecture for both instruction and data a single data path or bus is present.
Therefore the CPU performs a single operation at a time. It either performs Read/Write operation on data, or
fetches a set of instruction from memory. Hence instruction fetch and a data transfer operation cannot occur
simultaneously by using a common bus.
Let's see the block diagram of Von Neumann Architecture:

Types of Microcontroller on the basis of Service Provider


On the basis of Service Provider or Vendor the types of microcontroller are:

1) AVR: AVR microcontroller is developed by Atmel service provider, AVR architecture is based on the Harvard
architecture. It is based on Reduced Instruction Set Computers (RISC). AVR is not an acronym it is just a name
given to the RISC architecture based microcontroller.
2) PIC: PIC microcontroller is also a Harvard architecture based controller. PIC is an acronym stands for
"Peripheral Interface Controller". This type of microcontroller supports programming in C, Assembly and BASIC
C.

3) Hitachi: Hitachi microcontroller belongs to H8 family of the controller. H8 is name used in large family of 8-
bit, 16-bit and 32-bit microcontroller developed by Renesas Technology, founded in an early 1990s within Hitachi
semiconductors.
4) Motorola: Motorola microcontroller is highly integrated microcontroller that is used for high-performance data
manipulation operation. This microcontroller unit uses a System Integration Module (SIM), Time Processing Unit
(TPU) and Queued Serial Module (QSM).
5. PIC and PIC16f877a Introduction
PIC Introduction:

Peripheral Interface Controllers (PIC) is one of the advanced microcontrollers developed by microchip
technologies. These microcontrollers are widely used in modern electronics applications. A PIC controller
integrates all type of advanced interfacing ports and memory modules. These controllers are more advanced than
normal microcontroller like 8051. The first PIC chip was announced in 1975 (PIC1650). As like normal
microcontroller, the PIC chip also combines a microprocessor unit called CPU and is integrated with various
types of memory modules (RAM, ROM, EEPROM ,etc.), I/O ports, timers/counters, communication ports, etc.
All PIC microcontroller family uses Harvard architecture. This architecture has the program and data accessed
from separate memories so the device has a program memory bus and a data memory bus (more than 8 lines in
a normal bus). This improves the bandwidth (data throughput) over traditional von Neumann architecture where
program and data are fetched from the same memory (accesses over the same bus). Separating program and data
memory further allows instructions to be sized differently than the 8-bit wide data word. Now we will move to
PIC16F877A.
PIC16F877A Introduction:
Microcontroller PIC16F877A is one of the PICMicro Family microcontroller which is popular at this moment,
start from beginner until all professionals. Because very easy using PIC16F877Aand use FLASH memory
technology so that can be write-erase until thousand times. The superiority this RISC Microcontroller compared
to with other microcontroller 8-bit especially at a speed of and his code compression.
The 16F877A is a capable microcontroller that can do many tasks because it has a large enough programming
memory (large in terms of sensor and control projects) 8k words and 368 Bytes of RAM. This is enough to do
many different projects.
6. Features of PIC16F877A
The PIC16F877A CMOS FLASH-based 8-bit microcontroller is upward compatible with the PIC16C5x,
PIC12Cxxx and PIC16C7x devices. It features 200 ns instruction execution, 256 bytes of EEPROM data
memory, self programming, an ICD, 2 Comparators, 8 channels of 10-bit Analog-to-Digital (A/D) converter, 2
capture/compare/PWM functions, a synchronous serial port that can be configured as either 3-wire SPI or 2-wire
I2C bus, a USART, and a Parallel Slave Port.
High-Performance RISC CPU
 Lead-free; RoHS-compliant
 Operating speed: 20 MHz, 200 ns instruction cycle
 Operating voltage: 4.0-5.5V
 Industrial temperature range (-40° to +85°C)
 15 Interrupt Sources
 35 single-word instructions
 All single-cycle instructions except for program branches (two-cycle)
Special Microcontroller Features
 Flash Memory: 14.3 Kbytes (8192 words)
 Data SRAM: 368 bytes
 Data EEPROM: 256 bytes
 Self-reprogrammable under software control
 In-Circuit Serial Programming via two pins (5V)
 Watchdog Timer with on-chip RC oscillator
 Programmable code protection
 Power-saving Sleep mode
 Selectable oscillator options
 In-Circuit Debug via two pins
Peripheral Features
 33 I/O pins; 5 I/O ports
 Timer0: 8-bit timer/counter with 8-bit prescaler
 Timer1: 16-bit timer/counter with prescaler
 Can be incremented during Sleep via external crystal/clock
 Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler
 Two Capture, Compare, PWM modules
 16-bit Capture input; max resolution 12.5 ns
 16-bit Compare; max resolution 200 ns
 10-bit PWM
 Synchronous Serial Port with two modes:
 SPI Master
 I2C Master and Slave
 USART/SCI with 9-bit address detection
 Parallel Slave Port (PSP)
 8 bits wide with external RD, WR and CS controls
 Brown-out detection circuitry for Brown-Out Reset
Analog Features
 10-bit, 8-channel A/D Converter
 Brown-Out Reset
 Analog Comparator module
 2 analog comparators
 Programmable on-chip voltage reference module
 Programmable input multiplexing from device inputs and internal VREF
 Comparator outputs are externally accessible
7. Different Applications of Microcontroller
Microcontroller is termed as “Computer-on-a-Chip“. It is named so, because not only the CPU, but
RAM, ROM, I/O ports, Timer/Counter, Serial I/Os all are put together on a single microcontroller
chip. Microcontrollers are task specific and are essentially used for making Embedded Systems.
The below image shows very few examples for the application of microcontrollers in our day-to-day
used products. Actually wherever we need electronic automation, we use microcontroller. The
application area of microcontrollers is so vast, probably we won’t be able to finish up listing them
all. Here we will categorize different application areas of microcontrollers:
Figure: Application of microcontroller
i. Consumer Electronics Products:
Toys, Cameras, Robots, Washing Machine, Microwave Ovens etc. [any automatic home
appliance]
ii. Instrumentation and Process Control:
Oscilloscopes, Multi-meter, Leakage Current Tester, Data Acquisition and Control etc.
iii. Medical Instruments:
ECG Machine, Accu-Check etc.
iv. Communication:
Cell Phones, Telephone Sets, Answering Machines etc.
v. Office Equipment:
Fax, Printers etc.
vi. Multimedia Application:
Mp3 Player, PDAs etc.
vii. Automobile:
Speedometer, Auto-breaking system etc.
8. Differentiate between CISC and RISC
CISC is a Complex Instruction Set Computer. It is a computer that can address a large number of
instructions.
In the early 1980s, computer designers recommended that computers should use fewer instructions
with simple constructs so that they can be executed much faster within the CPU without having to
use memory. Such computers are classified as Reduced Instruction Set Computer or RISC.
The following points differentiate a CISC from a RISC –

CISC RISC

Larger set of instructions. Easy to program Smaller set of Instructions. Difficult to


program.

Simpler design of compiler, considering larger Complex design of compiler.


set of instructions.

Many addressing modes causing complex Few addressing modes, fix instruction
instruction formats. format.

Instruction length is variable. Instruction length varies.


Higher clock cycles per second. Low clock cycle per second.

Emphasis is on hardware. Emphasis is on software.

Control unit implements large instruction set Each instruction is to be executed by


using micro-program unit. hardware.

Slower execution, as instructions are to be read Faster execution, as each instruction is to be


from memory and decoded by the decoder unit. executed by hardware.

Pipelining is not possible. Pipelining of instructions is possible,


considering single clock cycle.

9. Architecture of PIC Microcontroller:


The architecture of Peripheral Interface Controller comprises of central processing unit (CPU), I/O
ports, A/D converter, memory organization, timers/counters, serial communication, interrupts,
oscillator and CCP module that are discussed in detailed below.
Central Processing Unit (CPU)
PIC microcontroller’s CPU is not different like other microcontroller CPU, which includes the ALU,
controller unit, the memory unit, and accumulator. ALU is mainly used for arithmetic and logical
operations. The memory unit is used to store the commands after processing. The control unit is used
to control the internal & external peripherals, and the accumulator is used to store the final results
and further process.
Memory Organization
The memory module in the PIC microcontroller architecture consists of Random Access Memory,
Read Only Memory and STACK.
RAM (Random Access Memory)
RAM is used to store the information temporarily in its registers. It is categorized into two banks,
each bank has so many registers. The RAM registers are categorized into two types, namely SFR
(Special Function Registers) and GPR (General Purpose Registers).
Special Function Registers
As the name implies, SFRs are used only for special purposes. These registers will work based on
the function assigned to them, and these registers cannot work as a normal register. For instance, if
you cannot use the STATUS register for storing the information, SFRs are used for viewing the status
of the program. So, a consumer cannot change the SFR’s function; the function is given by the retailer
at the time of built-up.
Memory Organization
The memory organization of Peripheral Interface Controller includes the following
 Read Only Memory (ROM)
 Electrically Erasable Programmable Read Only Memory (EEPROM)
 Flash Memory
 Stack
Figure: Architecture of PIC Microcontroller

Memory Organization
I/O Ports
The PIC microcontroller consists of 5-ports, namely Port A, Port B, Port C, Port D and Port E.
BUS
BUS is used to transfer & receive the data from one peripheral to another. It is categorized into two
types like data bus and address.Data Bus is used to transfer or receive the data.
BUS
The address bus is used to transfer the memory address from the peripherals to the central processing
unit. Input/Output pins are used to interface the exterior peripherals; both the UART & USART are
serial communication protocols, used to interface with serial devices such as GPS, GSM, IR,
Bluetooth, etc.
A/D Converters
A/D converter is used to convert analog voltage values to digital voltage values. An A/D module in
Peripheral Interface Controller comprises of 5-inputs for 28-pin devices & 8-inputs for 40-pin
devices. The operation of the A/D converter is controlled by special registers like ADCON0 &
ADCON1. The upper and lower bits of the converter are stored in registers like ADRESH and
ADRESL. In this process, it needs 5V of an analog reference voltage.

Analog to Digital converter


Timers/ Counters
PIC microcontroller has four-timer/counters wherein the one 8-bit timer and the remaining timers
have the choice to select 8 or 16-bit mode. Timers are used for generating accuracy actions, for
example, creating specific time delays between two operations.
Interrupts
PIC microcontroller consists of 20 internal & 3-external interrupt sources which are allied with
different peripherals like USART, ADC, Timers, and so on.
Serial Communication
Serial communication is the method for transferring one-bit data at a time sequentially over a
communication channel.

Figure: Serial Communication using MAX 232


(i) USART
The term USART stands for “Universal synchronous and Asynchronous Receiver” and Tx which is
a serial communication for two protocols. USART is used for transmitting & receiving the data bit
by bit over a single wire with respect to CLK pulses. The Peripheral Interface Controller consists of
two pins TXD & RXD. These pins are used for transmitting & receiving the data serially.
(ii) SPI Protocol
The term SPI (Serial Peripheral Interface) is used to send information between PIC microcontroller
and other peripherals like sensors, SD cards, and shift registers. This microcontroller supports 3-wire
SPI communications between two devices on a common CLK source. The data rate of this protocol
is more than that of the USART.
(iii)I2C Protocol
The term I2C stands for “Inter-Integrated Circuit”, and it is a serial protocol, used to connect low-
speed devices like EEPROMS, A/D converters, microcontrollers, etc. PIC microcontroller supports
this communication between two devices which can work as both Master & Slave device.
Oscillators
Oscillators are used for timing generation. This microcontroller comprises of external oscillators such
as crystal oscillators or RC oscillators. Where the crystal oscillator is associated with the two pins of
the oscillator. The capacitor value is connected to each pin that chooses the operation mode of the
oscillator. These modes are the high-speed mode, crystal mode, and the low-power mode. In the case
of RC oscillators, the resistor value and capacitor decide the CLK frequency and the clock frequency
range from 30 KHz to 4 MHz.
CCP Module
The term CCP stands for “capture/compare/PWM” where it works in 3-modes such as compare
mode, capture mode, and PWM mode.
Capture Mode
This mode captures the signal arrival time, or in other words, when the pin of this mode goes high, it
captures the Timer1 value.
Compare Mode
Compare mode performances as an analog comparator. When the value of the timer1 reaches a certain
reference value, then it produces an o/p.
PWM Mode
The PWM mode offers pulse width modulated o/p with a 10-bit resolution and programmable duty
cycle.
10. Explain General-purpose registers and SFR registers

General-purpose registers: General-purpose registers are used for storing temporary data and
results created during operation. For example, if the program performs a counting (for example,
counting products on the assembly line), it is necessary to have a register which stands for what we
in everyday life call “sum”. Since the microcontroller is not creative at all, it is necessary to specify
the address of some general purpose register by 1, after each product passes through a sensor, should
be created. Therefore, the microcontroller can execute that program because it now knows what and
where the sum which must be incremented is. Similar to this example, each program variable must
be reassigned some of general-purpose register.

SFR Registers: Special purpose registers are also Ram memory locations, but unlike general-
purpose registers, their purpose is predetermined during manufacturing process and cannot be
changed. Since their bits are physically connected to particular circuits on the chip (A/D converter,
serial communication module, etc.), any change of their contents directly affects the operation of
microcontroller or some of its circuits. For example, by changing TRISA register, the function of
each port A pin can be changed in a way it acts as input or output. Another feature of these memory
locations is that they have their names (registers and their bits), which considerably facilities program
writing. Since high-level programming language can use the list of all registers with their exact
addresses, it is enough to specify the register’s name in order to read or change its contents.

11. The key differences between microcontroller and microprocessor.


Differences between microcontroller and microprocessor:
12. Explain Von Neumann and Harvard architecture with suitable diagram.
Von Neumann Architecture
The Von Neumann architecture was first proposed by a computer scientist John von Neumann. In
this architecture, one data path or bus exists for both instruction and data. As a result, the CPU does
one operation at a time. It either fetches an instruction from memory, or performs read/write operation
on data. So an instruction fetch and a data operation cannot occur simultaneously, sharing a common
bus.

Von-Neumann architecture supports simple hardware. It allows the use of a single, sequential
memory. Today's processing speeds vastly outpace memory access times, and we employ a very fast
but small amount of memory (cache) local to the processor.
Harvard Architecture
The Harvard architecture offers separate storage and signal buses for instructions and data. This
architecture has data storage entirely contained within the CPU, and there is no access to the
instruction storage as data. Computers have separate memory areas for program instructions and data
using internal data buses, allowing simultaneous access to both instructions and data.
Programs needed to be loaded by an operator; the processor could not boot itself. In a Harvard
architecture, there is no need to make the two memories share properties.

13. Differentiate between Von-Neumann Architecture vs Harvard Architecture


The following points distinguish the Von Neumann Architecture from the Harvard
Architecture.

Von-Neumann Architecture Harvard Architecture

Single memory to be shared by both code Separate memories for code and data.
and data.
Processor needs to fetch code in a separate Single clock cycle is sufficient, as
clock cycle and data in another clock cycle. separate buses are used to access code and
So it requires two clock cycles. data.
Higher speed, thus less time consuming. Slower in speed, thus more time-
consuming.
Simple in design. Complex in design.

14. Compiler Directives


Any line in source code with leading # is taken as a compiler directive. The initial # can be
preceded or followed by whitespace (excluding new lines). The compiler directives are not case
sensitive.

You can use conditional compilation to select particular sections of code to compile while
excluding other sections. All compiler directives must be completed in the source file in which
they begun.

Directives #DEFINE and #UNDEF


Use directive #DEFINE to define a conditional compiler constant (“flag”). You can use any
identifier for a flag, with no limitations. No conflicts with program identifiers are possible
because the flags have a separate name space. Only one flag can be set per directive.

For example:

#DEFINE extended_format

Use #UNDEF to undefine (“clear”) previously defined flag.

Directives #IFDEF, #IFNDEF, #ELSE and #ENDIF


Conditional compilation is carried out by the #IFDEF and #IFNDEF directives. #IFDEF tests
whether a flag is currently defined, and #IFNDEF if the flag is not defined; i.e. whether a
previous #DEFINE directive has been processed for that flag and is still in force.
Directives #IFDEF and #IFNDEF are terminated with the #ENDIF directive and can have an
optional #ELSE clause:

#IFDEF flag THEN


block of code
[ #ELSE
alternate block of code ]
#ENDIF

First, #IFDEF checks if flag is defined by means of #DEFINE. If so, only block of code will be
compiled. Otherwise, alternate block of code in #ELSE (if any) will be compiled. #ENDIF ends
the conditional sequence. The result of the preceding scenario is that only one section of code
(possibly empty) is passed on for further processing. The processed section can contain
further conditional clauses, nested to any depth; each #IFDEF must be matched with a
closing #ENDIF.

Here is an example:

' Uncomment the appropriate flag for your application:


'#DEFINE resolution10
'#DEFINE resolution12

#IFDEF resolution10 THEN


// <code specific to 10-bit resolution>
#ELSE
#IFDEF resolution12 THEN
// <code specific to 12-bit resolution>
#ELSE
// <default code>
#ENDIF
#ENDIF

Unlike #IFDEF, #IFNDEF checks if flag is not defined by means of #DEFINE, thus producing the
opposite results.

Include Directive #I
The #I parameter directive instructs mikroBasic PRO for PIC to include the named text file in
the compilation. In effect, the file is inserted in the compiled text right after the #I
filename directive. If filename does not specify a directory path, then, in addition to searching
for the file in the same directory as the current unit, mikroBasic PRO for PIC will search for file
in order specified by the search paths.
To specify a filename that includes a space, surround the file name with quotation marks: #I
"My file".

There is one restriction to the use of include files: An include file can't be specified in the
middle of a statement part. In fact, all statements between the begin and end of a statement
part must exist in the same source file.

15. Memory Interfacing:


PIC16F877A comes with three memories Flash,RAM and EEPROM. Below table shows the
memory capacity of PIC16F877A:

Memory Size Description


FLASH 8k-bytes Used to store the programs
RAM 368-bytes Temporary/ScratchPad memory used during program execution.
EEPROM 256-bytes Used to store the non-volatile data across power cycles

EEPROM Registers
The below table shows the registers associated with PIC16F877A UART.

Register Description
EECON1 EEPROM read/Write Control register
EECON2 Used to execute special instruction sequence(0x55-0xAA) during write
EEDATA Holds the data to be Written/Read to/from EEPROM.
EEADR Hold the Eeprom memory address from where the data needs to be read/written.

Steps For Eeprom Write

1. Check the WR bit to see if a write is in progress and wait till it becomes zero.
2. Write the address to EEADR. Make sure that the address is not larger than the memory size
of the device.
3. Write the 8-bit data value to be programmed in the EEDATA register.
4. Clear the EEPGD bit to point to EEPROM data memory.
5. Set the WREN bit to enable program operations.
6. Disable interrupts (if enabled).
7. Write 55h to EECON2
8. Write AAh to EECON2
9. Set the WR bit
10. Restore the Interrupts.
11. Clear the WREN bit to disable program operations.
Steps For EEPROM Read

1. Check the WR bit to see if a write is in progress and wait till it becomes zero.
2. Write the address to EEADR from where the data needs to be read. Make sure that the
address is not larger than the memory size of the device.
3. Set the RD bit to start the read operation
4. Read the data from the EEDATA register.

Reference: https://exploreembedded.com/wiki/PIC_Internal_Eeprom
16. Data types in MikroC for Microcontroller:
There are several types of data that can be used in C programming language. A table below shows
the range of values which these data can have when used in their basic form.
Data type Description Size (number of bits) Range of values
char Character 8 0 to 255
int Integer 16 -32768 to 32767
float Floating point 32 ±1.17549435082 ·10-38 to
±6.80564774407 ·1038
double Double precision 32 from ±1.17549435082 ·10-
38
floating point to ±6.80564774407 ·1038

By adding prefix (qualificator) to any data type, the range of its possible values changes as well as
the number of memory bytes needed.
Data type Data type with Size (number of bits) Range
prefix
char signed char 8 -128 to 128
int unsigned int 16 0 to 65535
short int 8 0 to 255
signed short int 8 -128 to 127
long int 32 0 to 4294967295
signed long int 32 -2147483648 to
2147483647
17. Operators, Operations and Expressions in MikroC for Microcontroller:
An operator is a symbol denoting particular arithmetic, logic or some other operation. There are more than
40 operations available in C language, but at most 10-15 of them are used in practice. Every operation is
performed upon one or more operands which can be variables or constants. Besides, every operation features
priority execution and associativity as well.
ARITHMETIC OPERATORS
Arithmetic operators are used in arithmetic operations and always return positive results. Unlike unary
operations being performed upon one operand, binary operations are performed upon two operands. In other
words, two numbers are required to execute a binary operation. For example: a+b or a/b.
OPERATOR OPERATION
+ Addition
- Subtraction
* Multiplication
/ Division
% Reminder
ASSIGNMENT OPERATORS
There are two types of assignments in C language:
 Simple operators assign values to variables using the common '=' character. For example: a = 8
 Compound assignments are specific to C language and consist of two characters as shown in the table.
An expression can be written in a different way as well, but this one provides more efficient machine code.
OPERATOR EXAMPLE
Expression Equivalent
+= a += 8 a=a+8
-= a -= 8 a=a-8
*= a *= 8 a=a*8
/= a /= 8 a=a/8
%= a %= 8 a=a%8
INCREMENT AND DECREMENT OPERATORS
Increment and decrement by 1 operations are denoted by '++' and '--'. These characters can either precede or
follow a variable. In the first case (++x), the x variable will be first incremented by 1, then used in
expression. Otherwise, the variable will be first used in expression, then incremented by 1. The same applies
to the decrement operation.

OPERATOR EXAMPLE DESCRIPTION


++a
++ Variable "a" is incremented by 1
a++
--b
-- Variable "b" is decremented by 1
b--

RELATIONAL OPERATORS
Relational operators are used in comparisons for the purpose of comparing two variables which can be
integers ( int ) or floating point numbers (float). If an expression evaluates to true, a 1 is returned. Otherwise,
a 0 is returned. This is used in expressions such as ‘if the expression is true then...’

OPERATOR MEANING EXAMPLE TRUTH CONDITION


> is greater than b>a if b is greater than a
>= is greater than or equal a >= 5 If a is greater than or
to equal to 5
< is less than a<b if a Is less than b
<= is less than or equal to a <= b if a Is less than or equal
to b
== is equal to a == 6 if a Is equal to 6
!= is not equal to a != b if a Is not equal to b
LOGIC OPERATORS
There are three types of logic operations in C language: logic AND, logic OR and negation (NOT). For the
sake of clearness, logic states in tables below are represented as logic zero (0=false) and logic one (1=true).
Logic operators return true (logic 1) if the expression evaluates to non-zero, and false (logic 0) if the expression
evaluates to zero. This is very important because logic operations are commonly used upon expressions, not
upon single variables (numbers) in the program. Therefore, logic operations refer to the truth of the whole
expression. For example: 1 && 0 is the same as (true expression) && (false expression) The result is 0, i.e.
- False in either case.
OPERATOR LOGICAL AND
&& Operand1 Operand2 Result
0 0 0
0 1 0
1 0 0
1 1 1
OPERATOR LOGICAL OR
|| Operand1 Operand2 Result
0 0 0

0 1 1
1 0 1
1 1 1
OPERATOR LOGICAL NOT
! Operand1 Result
0 1
1 0
BITWISE OPERATORS
Unlike logic operations being performed upon variables, the bitwise operations are performed upon single
bits within operands. Bitwise operators are used to modify the bits of a variable. They are listed in the table
below:

OPERAND MEANING EXAMPLE RESULT

~ Bitwise complement a = ~b b=5 a = -5

<< Shift left a = b << 2 b = 11110011 a = 11001100

>> Shift right a = b >> 2 b = 11110011 a = 00011110

& Bitwise AND c=a&b a = 11100011 b = 11001100 c = 11000000

| Bitwise OR c=a|b a = 11100011 b = 11001100 c = 11101111

^ Bitwise EXOR c=a^b a = 11100011 b = 11001100 c = 00101111


18. Timers:
In many PIC examples, you will see delays that are designed to add pauses during code execution.
One example of such a delay includes the LED flashing code in the previous articles, which use a
simple for-loop to add a delay between the ON and OFF states of the LED. However, sometimes
such delays are not very useful, especially when accurate timing is needed.
When accurate timing is a necessity, very useful peripheral comes in: the timer! Unlike for-loop
delays, a timer can provide a very accurate source for timing events and creating delays of a specific
length. Typically, PICs have many different timers, so to keep things simple, we will only be looking
at timer0.
Timer0 in the PIC
Most PICs have a timer0, which is usually an 8-bit timer that can be clocked from multiple sources,
is used for other peripherals, and can generate interrupts upon overflowing. This makes it very useful
for crucial timing routines, but can be used as a generic timer as well. When using the timer, there
are two main ways which this can be done:
 Interrupt the PIC when the timer overflows (counts over 255 and resets back to 0)
 Probe the timer register and see what value it is currently at
Since we have not considered interrupts yet, we will focus on using the timer to make a simple 1ms
delay via polling. The first task when using the timer is to configure, which is done by configuring
registers associated with the timer. For the PIC16F819, the OPTION_REG holds the bits needed for
configuring the timer.
The first bit that needs setting is the clock source for the timer. The most common source is from the
internal instruction clock cycle (essentially the operating frequency/4), but you can also clock the
timer from an external clock source (which is fed into the T0CKI pin). In our example, we will clock
it from the PIC and NOT an external source.
The next bit that can be set is the clock edge, which determines if the timer increments on a rising
edge or falling edge; this is rarely used and so can be ignored for now.
The next bit, PSA, determines if the pre-scaler is assigned to the timer or to the watchdog. In this
example, we will assign the PSA to the watchdog for reasons that will be explained later.

Setting up timer0 on the PIC16F819 in XC8


With the timer configured, it's time to use it in some code to make a 1ms delay. The timer is clocked
from FOSC / 4 and with our FOSC being 500kHz, the timer will therefore increment at a rate of
125kHz (or once every 8us). As we want to make a delay of 1ms using this timer, we need to
determine how many times the timer will clock until it reaches a value that is approximately 1ms.
This is where a bit of mathematics comes in!
Therefore, the timer will have a value of 125 when 1ms has passed. So in our delay function, we reset
the timer value and then wait until the timer register is equal or greater to 125.

19. Interrupt:
An interrupt is a signal to the processor emitted by hardware or software indicating an event that
needs immediate attention. Whenever an interrupt occurs, the controller completes the execution of
the current instruction and starts the execution of an Interrupt Service Routine (ISR) or Interrupt
Handler. ISR tells the processor or controller what to do when the interrupt occurs. The interrupts
can be either hardware interrupts or software interrupts.
Hardware Interrupt
A hardware interrupt is an electronic alerting signal sent to the processor from an external device,
like a disk controller or an external peripheral. For example, when we press a key on the keyboard
or move the mouse, they trigger hardware interrupts which cause the processor to read the keystroke
or mouse position.
Software Interrupt
A software interrupt is caused either by an exceptional condition or a special instruction in the
instruction set which causes an interrupt when it is executed by the processor. For example, if the
processor's arithmetic logic unit runs a command to divide a number by zero, to cause a divide-by-
zero exception, thus causing the computer to abandon the calculation or display an error message.
Software interrupt instructions work similar to subroutine calls.
What is Polling?
The state of continuous monitoring is known as polling. The microcontroller keeps checking the
status of other devices; and while doing so, it does no other operation and consumes all its processing
time for monitoring. This problem can be addressed by using interrupts.
In the interrupt method, the controller responds only when an interruption occurs. Thus, the
controller is not required to regularly monitor the status (flags, signals etc.) of interfaced and inbuilt
devices.
Interrupts v/s Polling
Here is an analogy that differentiates an interrupt from polling −

Interrupt Polling
An interrupt is like a shopkeeper. If one The polling method is like a salesperson. The
needs a service or product, he goes to him salesman goes from door to door while requesting
and apprises him of his needs. In case of to buy a product or service. Similarly, the controller
interrupts, when the flags or signals are keeps monitoring the flags or signals one by one for
received, they notify the controller that they all devices and provides service to whichever
need to be serviced. component that needs its service.

Interrupt Service Routine


For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler. When an
interrupt occurs, the microcontroller runs the interrupt service routine. For every interrupt, there is a
fixed location in memory that holds the address of its interrupt service routine, ISR. The table of
memory locations set aside to hold the addresses of ISRs is called as the Interrupt Vector Table.

You might also like