0% found this document useful (0 votes)
5 views

Notes 2014

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

Notes 2014

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

DIGITAL SYSTEMS III

The learner is encouraged to read the text book and additional text given in the study guide
for finer details in the subjects covered in this document.

1. INTRODUCTION TO EMBEDDED C PROGRAMMING


Facts to note about C language

• C was developed in 1974 in order to write the UNIX operating system.


• C is more "low level" than other high level languages (good for MCU programming).
• C is supported by compilers for a wide variety of MCU architectures.
• C can do almost anything assembly language can do.
• C is usually easier and faster for writing code than assembly language.
• C is not as portable between architectures or compilers as everyone claims.
o ANSI language features ARE portable.
o Processor specific libraries are NOT portable.
o Processor specific code (peripherals, I/O, interrupts, special features) are NOT
• C is NOT as efficient as assembly.
o A good assembly programmer can usually do better than the compiler, no
matter what the optimization level – C WILL use more memory.
• Because of many shortcuts available, C is not always friendly to new users – hence
the need for comments.
• Not every line needs to be commented, but most blocks of code should be

1
Development Tools Data Flow

Figure 1: Development tools data flow

Figure 2: C Compiler

2
C Runtime Environment

• C Compiler sets up a runtime environment.


o Allocates space for stack.
o Initialize stack pointer.
o Allocates space for heap.
o Copies values from Flash/ROM to variables in RAM that were declared with
initial values.
o Clear uninitialized RAM.
o Disable all interrupts.
o Call main() function (where your code starts).
• Runtime environment setup code is automatically linked into application by most PIC
compiler suites.
• User modifiable if absolutely necessary.

FUNDAMENTALS OF C
A Simple C Program

3
• A variable must be declared before it can be used.
• The compiler needs to know how much space to allocate and how the values should
be handled.
• Sometimes, variables (and other program elements) are declared in a separate file
called a header file.
• Header file names customarily end in .h.
• Header files are associated with a program through the #include directive.

Table 1: Data types

COMMENTS
Comments are used to document a program's functionality and to explain what a particular
block or line of code does. Comments are ignored by the compiler, so you can type anything
you want into them. Comments can be nested.

• Two kinds of comments may be used:


o Block Comment /* This is a comment */
o Single Line Comment // This is also a comment

4
2. INTRODUCTION TO MPLAB-X
Why make a completely new MPLAB?

• MPLAB 6-8 code base has run its course:


o IDE lacking several modern features
o Difficult to add many requested features
o Not easily extensible by 3rd parties
o Lacking some infrastructure for advanced high-level language development
o Limited to the Windows platform
• The new platform provides:
o A mature IDE proven through years of use
o A modern IDE with all the latest features
o A well-documented, extensible architecture
o Many requested features already present
o Architected for high-level language support
o Runs on Windows, Mac and Linux
o A rich ecosystem of plug-ins
o PC and embedded development in same IDE
o File structure that doesn't require IDE
o Many new features not previously available in MPLAB

5
Table 2: Major differences between MPLAB 8 and MPLAB-X

MPLAB 8 MPLAB-X
USB Drivers

ICDs and Real ICE use proprietary drivers. ICDs and Real ICE™ use open source
drivers.

USB Communications Link with Hardware Tools

Link established when tool selected or Link established when debug session started
workspace opened with tool already selected

Link severed when MPLAB is closed Link severed when debug session terminated

Link is always on while tool enabled Link is always off except when actively
debugging

Projects and Workspaces

Projects contain: Projects contain:

Basic project settings, project files Everything – no workspaces needed


and locations, target device
Workspaces contain: Project Groups:

Open projects, window placement, List of projects to simplify opening up


build and debug tools multiple related projects that are frequently
opened together

Project Files and Structure

Projects and workspaces represented by


individual files that may be double clicked to
Project represented by specific directory
open the project or workspace:
structure containing XML files
• *.mcp (project)
• *.mcw (workspace)
There is no project file to double click

Project must be opened from within IDE

6
Debug/Release Build Settings

Debug/Release combo box must be explicitly Debug/Release implied by specific build


chosen for the desired build type command

• Build (Make)
• Clean and Build (Build All)
o Run Project
• Make or
o Program Target
• Build All
• Debug Run Project

MPLAB 8 IDE

Figure 3: MPLAB IDE

7
MPLAB-X IDE

Figure 4: MPLAB-X IDE

8
PARTS OF THE IDE

2 3

4
5

Figure 5: Partsof MPLAB-X IDE

1. Main Toolbar

2. Project Window

3. Editor Window with Editor Toolbar, Glyph Margin and Error Stripe.

4. Navigator Window

5. Output Window

9
USB Driver Switcher Utility

• Allows users to continue using MPLAB 8.x side-by-side with MPLAB X


• Tool must be connected when switching

Figure 6: Device driver switcher

The rest of the MPLAB-X IDE is covered in the LAB MANUAL and will be
implemented during the practical sessions.

10
3. PIC ARCHITECTURE AND ASSEMBLY LANGUAGE
PROGRAMMING

Read Chapter 2 in the prescribed text book, Section 1 of the PIC16F84, and Section 1 of the
PIC18F8722 family data sheets.

The PIC16F84 device has 80 pins, 13 I/O pins, 1 Kwords program memory, 68 bytes data
memory (RAM), 64 bytes data EEPROM, and 2 bidirectional ports.

The PIC18F8722 device has 80 pins, 128 Kbytes flash program memory, 16 channels A/D
converter, 9 bidirectional ports, and external memory bus configurable for 8 and 16 bit
operation.

Data is stored in registers. To program in assembly language, the learner must understand the
registers and architecture of given CPU and the role they play in data processing. The
instruction set summary is used to write usable program. To program in C language there is
no need to understand the architecture.

The most commonly used registers are: WREG, STATUS, PORT, TRIS, LATCH, TIMERS
and control registers.

The registers may be classified into special function registers (SFRs) and general purpose
registers (GPRs) and may be divided into banks. The bank structures differ from
microcontroller family to microcontroller family and bank switching is critical. The registers
may be accessed directly or indirectly. The memory map for the PIC18F8722 device is
complicated and there is a register dedicated for bank selection.

11
Figure 7: PIC16F84 pin diagram

Figure 8: PIC16F84 architecture

12
Figure 9: PIC16F84memory map

13
Figure 10: PIC18F8722 pin diagram

14
Figure 11: PIC18F8722 architecture

15
Figure 12: PIC18F8722 ALU

Task 1:

Develop a digital system demonstrating the application of a PIC16F84 device in reading an


input from the port pins and sending an output to the port pins. This task will demonstrate
the application of assembly language in developing a program.

Task 2:

Develop a digital system demonstrating the application of a PIC18F8722 device in solving a


problem. This task will demonstrate the application of C language in developing an
application. Further studies will build onto this task to demonstrate I/O pins programing,
input reading, and other applications. Chapters 1 to 6 of the prescribed text book give good
examples of programing the PIC18F8722 device in assembly language.

16
4. PIC PROGRAMMING IN C LANGUAGE

Read Chapter 7 in the prescribed text book. The learner is encouraged to master the
information discussed in sections 1 to 3 of this document. Reference to other text will be
given in due course.

Example 1: (7-1)

Write a C program to send values 00 – FF to port B. Run the program simulation in


MPLAB-X and use the watch window to observe the affected registers and variables (TRISB,
PORTB, z).

Solution:

#include <p18f8722.h>
void main(void)
{
unsigned char z;
TRISB = 0;
for(z=0; z<=255; z++)
PORTB = z;
while(1);
}

Discuss the program line by line.

Example 2: (7-2)

Write a C program to send hex values for ASCII characters of 0, 1, 2, 3, 4, 5, A, B, C and D


to port C. Run the program simulation in MPLAB-X and observe the affected registers and
variables. Values: 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x41, 0x42, 0x43, and 0x44 are
displayed on port C (hex values for the list in mynum[]). Observe that the variable mynum[]
has 11 characters while 10 characters are listed.

17
Solution:

#include <p18f8722.h>
void main (void)
{
unsigned char mynum[] = "012345ABCD";
unsigned char z;
TRISC = 0;
for(z=0; z<10; z++)
PORTC = mynum[z];
while(1);
}

Example 3: (7-3)

Write a C18 program to toggle alternate bits of port D. Run the MPLAB-X simulator to see
how alternate pins of port D toggle.

Solution:

#include <p18f8722.h>
void main(void)
{
TRISD = 0;
for( ; ; )
{
PORTD = 0x55;
PORTD = 0xAA;
}
}

How can you change the number of times the port is toggled? Practice with 1000 times,
50 000 times and 100 000 times. Practice the for loop using assembly language.

18
Example 4: (7-4)

Write a C18 program to send values -4 to +4 to port E. Run the MPLAB-X simulator to
observe the output. Revisit chapter 5 in the prescribed text book to revise signed numbers.

Solution:

#include "p18f8722.h"
void main(void)
{
char num[] = {+1, -1, +2, -2, +3, -3, +4, -4};
unsigned char z;
TRISE = 0;
for(z=0; z<8; z++)
PORTE = num[z];
while(1);
}

Example 5: (7-7)

Write a C18 program to toggle the bits of port F at regular intervals of 250 ms assuming the
crystal frequency of 8 MHz. Observe that the port F bits do not change noticeably.
Investigate the cause and the possible solution. Attempt toggling different ports.

Solution:

#include <p18f8722.h>
void MSDelay(unsigned int);
void main(void)
{
TRISF = 0;
while(1)
{
PORTF = 0xAA;
MSDelay(250);
PORTF = 0x55;
MSDelay(250);
}
}

void MSDelay(unsigned int itime)


{
unsigned int i; unsigned char j;
for(i=0; i<itime; i++)
for(j=0; j<165; j++);
}

19
5. PIC I/O PORT PROGRAMMING
Read Chapters 4&7 in the prescribed text book, and Section 11 of the PIC18F8722 family
data sheet. Reference to other text will be given in due course.

The PIC18F8722 has 9 bidirectional ports A to J (fgure…), labelled as PORTA, PORTB, up


to PORTJ, with 70 I/O pins. Each port has three registers for its operation. These registers
are:

• TRIS register (Data Direction register)


• Port register (reads the levels on the pins of the device)
• LAT register (output latch)

The Data Latch (LAT register) is useful for read-modify-write operations on the value that
the I/O pins are driving. The TRISx register is used for the purpose making a given port or
port pin input or output. The whole port can be made input or output, or individual pins can
be made input or input. Setting a TRISx bit will make the corresponding PORTx pin input.
Clearing a TRISx bit will make the corresponding PORTx pin output. Reading the port
register reads the status of the pins. Writing to the port register will write to the latch. Read-
modify-write operations take place in the LAT register. Most I/O pins are multiplexed with
other application tasks.

20
Example6: (7-10)

Write a C18 program that gets a byte from port B and send it to port C. In this example, port
B is made input and port C is made output.

Solution:

#include <p18f8722.h>
void MSDelay(unsigned int);
void main (void)
{
unsigned char mybyte;
TRISB = 0xFF;
TRISC = 0;
while(1)
{
mybyte = PORTB;
MSDelay(500);
PORTC = mybyte;
}
}

void MSDelay(unsigned int itime)


{
unsigned int i;
unsigned char j;
for(i=0; i<itime; i++)
for(j=0; j<165; j++);
}

This example demonstrates programing the I/O ports as input and output and reading input
data and displaying it as output. The instruction TRISB =0xFF; puts 1’s in all bits of TRISB
and makes PORTB input. The instruction TRISC = 0; puts 0’s in all bits of TRISC and
makes PORTC output.

21
Example 7: (7-12)

Write a C18 program that toggles one bit (RD6) continuously.

Solution:

#include "p18f8722.h"
#define pin PORTDbits.RD6
void main(void)
{
TRISDbits.TRISD6 = 0;
while(1)
{
pin = 1;
pin = 0;
}
}

The instruction #define pin PORTDbits.RD6 is a directive that tells the microcontroller to
substitute the word ‘pin’ with pin 6 of port D (RD6). This is the skill designed to use short
instructions and make the program easy to read. The instruction TRISDbits.TRISD6 = 0;
makes RD6 output.

22
Example 8: (7-13)

Design a digital system consisting of PIC18F8722 microcontroller, switch connected to RA1


and the DC motor connected to RB1. If the switch is pressed the motor will run. If the switch
is not pressed the motor is off. Depending on the application, the output can be a “1” or a
square wave of a certain frequency and duty cycle. This is a simple demonstration; minor
modification may be required in real-time implementation. Use the PIC18 Explorer demo
board to simulate this example. The learner is encouraged to practice with multiple
inputs/outputs. Examples on data and memory manipulation may be discussed later.

Solution:

A. The schematic circuit design

+5V

10k 10k

MCLR

RA1 RB1
mot

PIC18F8722

Figure 13: Motor controller circuit

B. The program

#include <p18f8722.h>
#define switch PORTAbits.RA1
#define mot PORTBbits.RB1
void main()
{
TRISAbits.TRISA1 = 1;
TRISBbits.TRISB1 = 0;
while (1)
{
If(switch == 1)
mot = 0;
else
mot = 1;
}
}

23
6. SERIAL PORT PROGRAMMING IN C LANGUAGE
Read Chapters 7&10 in the prescribed text book and section 19 of the PIC18F8722 family
data sheet. Reference to other text will be given in due course.

Serializing is a technique of sending or receiving a byte of data one bit at a time through a
single pin of a microcontroller. This can be done in software and in hardware.

6.1 Software serial programing

Data is transferred one bit at a time and the sequence of data and spacing between bits is
controlled in software. This technique can be used when interfacing devices such as LCDs,
ADCs, EEPROMs, etc.

Example 9: (7-30)

Write a C18 program to send out the value 41H serially via RA2. The LSB should go out
first. This pin is selected to match the LCD connection in the demo board. Note that port A
pins are analog I/O pins by default. The learner is encouraged to practice sending out the
MSB first.

Solution:

+5V

10k
DB0 D0
DB1 D1
MCLR DB2 D2
DB3 D3
RA2 DB4 D4
RC3 DB5 D5
RC4 DB6 D6
DB7 D7
P IC18F8722 RE
RS
R/W

MCP23S17 LCD
SPI Expander
Figure 14: SPI connection

24
// Serializing data via RA2 (shifting right)
#include <p18f8722.h>
#define TX PORTAbits.RA2
void main(void)
{
unsigned char conbyte = 0x41;
unsigned char OUTREGLSB;
unsigned char i;
OUTREGLSB = conbyte;
TRISAbits.TRISA2 = 0;
ADCON1 = 0xF;
for(i=0; i<8; i++)
{
TX = OUTREGLSB & 0x01;
OUTREGLSB = OUTREGLSB >> 1;
}
}

Simulate the source code using the demo board and discuss the source code line by line.

Example 10: (7-32)

Write a C18 program to receive a byte serially via RA0 and place the byte on port D. The
LSB is received first. Simulate using the demo board and discuss the source code. Practice
receiving an MSB first.

Solution

// Reading data via RA0 and (shifting right)


#include <p18f8722.h>
#define RX PORTAbits.RA0
void main(void)
{
unsigned char i;
unsigned char INREG = 0;
TRISAbits.TRISA0 = 1;
TRISD = 0;
ADCON1 = 0x0F;
for(i=0; i<8; i++)
{
INREG = INREG >> 1;
INREG |= (RX & 01) << 7;
}
PORTD = INREG;
}
25
6.2 Hardware serial programing

When microcontrollers communicate data is provided one byte at a time. In serial


communication a byte is transferred one bit at a time. The byte of data must be converted to
serial bits using the parallel-in serial-out shift register on the transmit side. At the receiving
side a serial-in parallel-out shift register is used to receive serial data and pack them into a
byte. Serial data communication uses synchronous method (a block of data is transferred) or
asynchronous method (single byte is transferred). There must be a protocol stipulating how
data is packed, how many bits constitute a character and when the data begins and end. In
duplex communication data can be transmitted and received. In simplex transmission data is
in one direction.

Hardware serial communication is controlled by registers: SPBRG, TXREG, RCSTA, and


TXSTA.

26
Example 11: (10-11)

Write a C program for the PIC18 microcontroller to transfer the letter “G” serially at 9600
baud rate. Use 8-bit data and 1 stop bit. Assume XTAL = 10 MHz. Practice transmitting a
message.

Solution:

#include <p18f8722.h>
void main(void)
{
TXSTA = 0x20;
SPBRG = 15;
TXSTAbits.TXEN = 1;
RCSTAbits.SPEN = 1;

while(1)
{
TXREG = 'G';
while(PIR1bits.TXIF == 0);
}
}

Example 12: (10-13)

Write a C18 program to receive bytes of data serially and put them on port B. Set the baud
rate at 9600, 8-bit data, and 1 stop bit.

Solution:

#include <p18f8722.h>
void main(void)
{
TRISB = 0;
RCSTA = 0x90;
SPBRG = 15;

while(1)
{
while(PIR1bits.RCIF == 0);
PORTB = RCREG;
27
}
}

7. LCD AND KEYBOARD INTERFACING


Read Chapter 12 of the prescribed text book and section 19 of the PIC18F8722 family data
sheet.

7.1 LCD

The LCD is used to display characters. The commonly used LCD has 2 rows and 16
character positions (2X16). It consists of 3 power connections, 3 control lines and 8 data
lines. It can be operated in 8-bit mode and 4-bit mode. In the explorer 18 demo board, the
SPI communication is used to connect the microcontroller to the LCD. The SPI
communication uses three wires, chip select, clock and data.
R/W
VSS
VCC

RS
VEE

D7 D6 D5 D4 D3 D2 D1 D0
E

Figure 15: 2x16 LCD

VCC provides +5V, VSS provides ground, VEE is for LCD contrast control.

The LCD has a controlling microcontroller (HD44780) which has 2 registers, the instruction
command code register and the data register. If RS = 0, the command register is selected. If
RS = 1, the data register is selected.

R/W pin allows user to write information to the LCD or to read information from LCD. If
R/W = 0, write to LCD. If R/W = 1, read from LCD.

E is the enable pin used to latch information presented to the LCD data pins. A pulse on E
enables the LCD to read the data present during the falling edge.

28
The D0 to D7 pins used to load data to the LCD during the write instruction or from the LCD
during the read instruction. During 8-bit mode, the byte is loaded to the pins then a pulse is
applied on E. During the 4-bit mode, the upper nibble is transmitted first, then the lower
nibble. For SPI operation, a byte is transmitted serially 1-bit at a time as discussed in section
6. There is a specific sequence for displaying data on the LCD, can use delays or busy signal.

Example 13: (12-1C)

Write a C18 program that send letters “M”, “D” and “E” to the LCD using delays.

M D E
R/W
VSS
VCC

RS
VEE

D7 D6 D5 D4 D3 D2 D1 D0
E

+5V

10k

MCLR

D7
D6
PIC18F8722 D5
D4
D3
D2
D1
D0

Figure 16: LCD interface

Solution:

#include <p18f8722.h>
#define ldata PORTD
#define rs PORTBbits.RB0
#define rw PORTBbits.RB1
#define en PORTBbits.RB2

void MSDelay(unsigned int itime);


void lcdcmd(unsigned char value);
void lcddata(unsigned char value);

29
void main(void)
{
TRISD = 0;
TRISB = 0;
en = 0;
MSDelay(250);
lcdcmd(0x38);
MSDelay(250);
lcdcmd(0x0E);
MSDelay(15);
lcdcmd(0x01);
MSDelay(15);
lcdcmd(0x06);
MSDelay(15);
lcdcmd(0x86);
MSDelay(15);
lcddata('M');
MSDelay(15);
lcddata('D');
MSDelay(15);
lcddata('E');
}

void lcdcmd(unsigned char value)


{
ldata = value;
rs = 0;
rw = 0;
en = 1;
MSDelay(1);
en = 0;
}

void lcddata(unsigned char value)


{
ldata = value;
rs = 1;
rw = 0;
en = 1;
MSDelay(1);
en = 0;
}

void MSDelay(unsigned int itime)


{
unsigned int i, j;
for(i=0; i<itime; i++)
for(j=0; j<135; j++);
}

30
7.2 Keypad

The keypad is organised in a matrix of rows and columns. When a key is pressed a row and a
column make contact. The program scans the keys continuously in order to identify which
one is pressed. This study will use the key scanning method of detection where the
microcontroller sends a “0” on the columns and scan the rows.

Figure 17: Keypad matrix

Develop a digital system application that reads the keypad and display the value of the key on
the LCD. The application must be implemented on the demo board.

31
8. INTRODUCTION TO ADC AND DAC.
Read chapter 13 of the prescribed text book and section 21 of the PIC18F8722 family data
sheet.

Analog-to-digital converters are widely used in data acquisition. The AD converter module
for thePIC18F8722 has 16 inputs. An analog signal is converted to a 10-bit digital number.
The number of bits (n) in a digital number determines the resolution of the ADC. The step
Vref
size of the ADC is given by and for the 10-bit ADC. The step size is 4.88 mV for a 10-
2n
bit resolution and 5V reference. In addition to resolution the conversion time is important in
judging the ADC. The conversion time is the time taken by the ADC to convert the analog
input to a digital number depending on the clock input. The output voltage is given by
Vin
Dout = .
Step size

Example 14: (13-1)

Determine the D0-D9 output if the analog input is 2.8V while the reference is 5V and the
resolution is 10-bit.

Solution:

Vref 5V
The step size = n
= = 4.88 mV
2 1024

Vin
Dout =
Step size

2.8V
=
4.88mV
32
= 574

= 1000111110

Analog-to-digital conversion follows a specific sequence:

1. Select channel.

2. Activate the start conversion (SC) signal to start the conversion of analog input.

3. Keep monitoring the end of conversion (EOC) signal.

4. After the EOC has been activated, read data out of the ADC.

The converted output is held by two special function registers, ADRESH and ADRESL with
the option of right or left justification. The reference voltage, Vref, can be the Vdd of the
circuit or a separate supply. The conversion time is determined by the oscillator frequency
and must not be shorter than 1.6 ms. AD conversion is programmed using associated special
function registers:

• A/D Result High Register (ADRESH)


• A/D Result Low Register (ADRESL)
• A/D Control Register 0 (ADCON0)
• A/D Control Register 1 (ADCON1)
• A/D Control Register 2 (ADCON2)

The ADCON0 register is used to select the analog channel, switch the ADC on and to start
the conversion.

33
The ADCON1 register is used to select the reference voltage, Vref, and port configuration.

The ADCON2 register is used for result justification, to select acquisition time and to select
the AD conversion clock.

The conversion time is defined in terms of Tad, the time to convert one bit. To calculate Tad,
select the conversion clock source of Fosc/2, Fosc/4, Fosc/8, Fosc/16, Fosc/32 or Fosc/64.
Fosc is the crystal frequency. For PIC18 microcontrollers, the conversion time is 12 × Tad.
AD conversion must be started after the acquisition time (Tacq = 15 µ s typical). Refer to
examples 13-4 and 13-5 in the prescribed text book.

Example 15: (Prog 13-1)

Write a C18 program that gets data from channel 0 (RA0) of ADC and displays the result on
port C and port D. This is done every quarter second.

Solution:

+5V

10k
10k C7
C6
C5
MCLR C4
C3
C2
C1
C0

RA0
100k D7
D6
PIC18F8722 D5
D4
D3
D2
D1
D0

Figure 18: ADC setup

34
#include <p18f8722.h>
void DELAY(unsigned int itime);
void main(void)
{
TRISC = 0;
TRISD = 0;
TRISAbits.TRISA0 = 0;
ADCON0 = 0x81;
ADCON1 = 0xCE;

while(1)
{
DELAY(1);
ADCON0bits.GO = 1;
while(ADCON0bits.DONE ==1);
PORTC = ADRESL;
PORTD = ADRESH;
DELAY(250);
}
}

void DELAY(unsigned int itime)


{
unsigned int i, j;
for(i=0; i<itime; i++)
for(j=0; j<135; j++);
}

35

You might also like