[go: up one dir, main page]

0% found this document useful (0 votes)
30 views40 pages

PSDL Final Manual Updated (Footer21-22)

The document provides an overview of Embedded C programming, detailing its syntax and structure, as well as differences from standard C. It includes examples of simple programs such as adding two numbers, transferring memory, and implementing a menu-driven multiplication program. Additionally, it describes hardware interfacing with a PIC microcontroller and outlines the steps for programming and debugging using MPLAB IDE.

Uploaded by

shrigujar25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views40 pages

PSDL Final Manual Updated (Footer21-22)

The document provides an overview of Embedded C programming, detailing its syntax and structure, as well as differences from standard C. It includes examples of simple programs such as adding two numbers, transferring memory, and implementing a menu-driven multiplication program. Additionally, it describes hardware interfacing with a PIC microcontroller and outlines the steps for programming and debugging using MPLAB IDE.

Uploaded by

shrigujar25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Experiment No.

1 : Study of Embedded C programming language (Overview, syntax, One simple


program like addition of two numbers).

Introduction to Embedded C Programming Language

Before going in to the details of Embedded C Programming Language and basics of Embedded C Program, we
will first talk about the C Programming Language.

The C Programming Language, developed by Dennis Ritchie in the late 60’s and early 70’s, is the most popular
and widely used programming language. The C Programming Language provided low level memory access
using an uncomplicated compiler (a software that converts programs to machine code) and achieved efficient
mapping to machine instructions.

The C Programming Language became so popular that it is used in a wide range of applications ranging from
Embedded Systems to Super Computers.

Embedded C Programming Language, which is widely used in the development of Embedded Systems, is an
extension of C Program Language. The Embedded C Programming Language uses the same syntax and
semantics of the C Programming Language like main function, declaration of datatypes, defining variables,
loops, functions, statements, etc.

The extension in Embedded C from standard C Programming Language include I/O Hardware Addressing,
fixed point arithmetic operations, accessing address spaces, etc.

Difference between C and Embedded C:There is actually not much difference between C and Embedded C
apart from few extensions and the operating environment. Both C and Embedded C are ISO Standards that have
almost same syntax, datatypes, functions, etc.

Embedded C is basically an extension to the Standard C Programming Language with additional features like
Addressing I/O, multiple memory addressing and fixed-point arithmetic, etc.

C Programming Language is generally used for developing desktop applications, whereas Embedded C is used
in the development of Microcontroller based applications.

Basic Structure of an Embedded C Program (Template for Embedded C Program)

The next thing to understand in the Basics of Embedded C Program is the basic structure or Template of
Embedded C Program. This will help us in understanding how an Embedded C Program is written.

1
The following part shows the basic structure of an Embedded C Program.

o Multiline Comments . . . . . Denoted using /*……*/


o Single Line Comments . . . . . Denoted using //
o Preprocessor Directives . . . . . #include<…> or #define
o Global Variables . . . . . Accessible anywhere in the program
o Function Declarations . . . . . Declaring Function
o Main Function . . . . . Main Function, execution begins here
{
Local Variables . . . . . Variables confined to main function
Function Calls . . . . . Calling other Functions
Infinite Loop . . . . . Like while(1) or for(;;)
Statements . . . . .
….
….
}
o Function Definitions . . . . . Defining the Functions
{
Local Variables . . . . . Local Variables confined to this Function
Statements . . . . .
….
….
}
Before seeing an example with respect to 8051 Microcontroller, we will first see the different components in the
above structure.

Different Components of an Embedded C Program

Comments: Comments are readable text that are written to help us (the reader) understand the code easily.
They are ignored by the compiler and do not take up any memory in the final code (after compilation).

There are two ways you can write comments: one is the single line comments denoted by // and the other is
multiline comments denoted by /*….*/.

Preprocessor Directive: A Preprocessor Directive in Embedded C is an indication to the compiler that it must
look in to this file for symbols that are not defined in the program.

In C Programming Language (also in Embedded C), Preprocessor Directives are usually represented using #
symbol like #include… or #define….

2
In Embedded C Programming, we usually use the preprocessor directive to indicate a header file specific to the
microcontroller, which contains all the SFRs and the bits in those SFRs.

In case of 8051, Keil Compiler has the file “reg51.h”, which must be written at the beginning of every
Embedded C Program.

Global Variables: Global Variables, as the name suggests, are Global to the program i.e., they can be accessed
anywhere in the program.

Local Variables: Local Variables, in contrast to Global Variables, are confined to their respective function.

Main Function: Every C or Embedded C Program has one main function, from where the execution of the
program begins.

STEPS TO BE FOLLOWED FOR PROGRAMMING WITH PIC

1. MPLAB X Programming IDE.


Step1: Creating a new project
➢ Go to the File Tab.
➢ Click on New Project.
➢ Step1: Choose Project:
➢ Select: Microchip Embedded -> Standalone Project. Click Next.
Step2: Select Device:

➢ Select: Family -> Advanced 8 Bit MCU (PIC18).


➢ Select: Device: PIC18F4550. Click Next.
Step3: Select Tool: Simulator. Click Next.
Step4: Select Compiler ->XC8. Click Next.
Step5: Select Project Name and Folder.
➢ Give Project Name.
➢ Select project Location using Browse Button.
➢ Uncheck Set as main project option.
➢ Click Finish..
Step6: Creating a new Source file and Header File.
➢ Go to the Project location in the Project window.
➢ Click the + sign to open the project space.
➢ Right Click on the Source Files folder (for a C file) and Header files (for a .h file).
➢ New - > C Source file / or C Header File.
Step7: Opening an existing project.
➢ Go to the File Tab.
➢ Select Open Project.
Browse to the location and select the project name.X file (project file). Click on Open
Project
2. Adjusting application for Boot loader.
Step 1: Go to Project window and Right Click on the Project folder.
Go to Properties.

3
Select XC8 linker.
In Option categories ->Select memory model.
In Code offset section type 800
Click Apply button and OK button.
3. Compiling Project.

Step1: Go to project window.


➢ Right Click on the project folder and select Build or Clean and Build.
Step2.Executable Flashing Tool (PICLoader.exe).
➢ Connect the USB Cable to the Board.
➢ Double Click the PICloader.exe.
➢ Go to Programs -> Settings.
➢ Select the USB or serial com port. Click OK.

Step3: Go to Programs -> Break/Reset Mode or Press F3. Step4: Press
the Reset Switch on the Micro-PIC18F Board.Step5: Go to Programs -
>Bootloader Mode or Press F4. Step6 : Select Hex file :
File -> Open -> Browse to location.
Project folder -> dist -> default->production.- Double click on every
Step7: Go to Programs -> Write Device or Press F6
Step8: Press Reset on the board to Run the program.

4
Assignment No.1: Addition of two 8 bit Nos:

#include <P18F4550.h>

void main(void)
{
Unsigned int i, j, x;
TRISB=0; // port b as O/P
LATB=0;
i=0x04;
j=0x05;
x=i+j;
PORTB=x;
PORTC=i;
PORTD=j;

Out put : Address Name Hex Decimal Binary Char


F81 LATB 0x09 09 00001001 “-“

5
How to see the Result

1. Write the program


2. Debug the project – Check for the errors
If No errors – Build successful will appear on the OUTPUT window
3. Go to Debug window ---Discreet debug operation
—build for debugging
- Launch for debugger option
- For single stepping press F8
4. To see the result: click on Window tab on Navigation bar
◼ Click on PIC Memory Views
◼ Select option required
◼ Window will appear go to required location and
observe the result by doing single stepping

6
Experiment No. 2 : Write an Embedded C program to add array of n numbers.

Addition of numbers in array


/*
* File: newmain.c

*/

#include <stdio.h>
#include <stdlib.h>
#include <pic18f4550.h>

void main(void) {

int i,sum,n;

int number[] = {1,2,3,4,5,6,7,8,9,10}; // array of 10 numbers

sum = 0; // initialize sum as zero

for(i=0; i<=9;i++){ //indexing start from 0 to 9


sum = sum+number[i];
}

TRISB =0; //initialize Port_B as output


PORTB = sum; // from sum to PORT_B

//n = 0xFF + 0XFF;


}

7
Experiment No. 3 : Write an Embedded C program to transfer elements from one location to
another for following: i) Internal to internal memory transfer ii) Internal to external memory
transfer.

I)Memory Transfer

/*
* File: mem_transfer.c

* Created on January 25, 2021, 9:49 PM


*/

#include <stdio.h>
#include <stdlib.h>
#include <pic18f4550.h>
/*
*
*/
void main(void) {

int temp,i;
int source1[] = {0x21,0x22,0x23,0x24,0x25}; // source mem block
int dest[] = {0x00,0x00,0x00,0x00,0x00}; // destination mem block

for(i=0; i<=4;i++){ // counter = 5

dest[i] = source1[i]; // source to destination

}
}

8
II) Memory Exchange

/*

* File: mem_xchg.c

*/

#include <stdio.h>

#include <stdlib.h>

#include <pic18f4550.h>

void main(void) {

int temp,i;

int source1[] = {0x21,0x22,0x23,0x24,0x25};

int dest[] = {0x99,0x99,0x99,0x99,0x99};

for(i=0; i<=4;i++){

temp = source1[i];

source1[i] = dest[i];

dest[i] = temp;

9
Experiment No. 4 : Write an Embedded C menu driven program for : i) Multiply 8 bit
number by 8 bit number.

Multiplication

/*
* File: mul_number.c
*
*/

#include <stdio.h>
#include <stdlib.h>
#include <pic18f4550.h>

//multiplication using successive addition


void main(void) {
//static int v_mem[] = 0x55; @0x0005
int num1, num2;
int result,i;

result = 0;
num1 = 0x23;
num2 = 0x10;

for(i=1; i<=num2; i++)


{
result = result + num1;
}

TRISB =0;
PORTB = result;

10
Experiment No. 5 : . Write an Embedded C program for sorting the numbers in ascending
and descending order.

Sorting the array

#include <stdio.h>
#include <stdlib.h>
#include <pic18f4550.h>

void main(void) {
int i,j,temp;
int num_asc[] = {10,2,5,1,6};

for(i=0; i<=4; i++){ // point to LHS number


for(j=i+1;j<=4;j++) // point to RHS number
if (num_asc[i] > num_asc[j]){ // if LHS > RHS , change the position
temp = num_asc[i];
num_asc[i] =num_asc[j];
num_asc[j]= temp;
}
}
}

11
Experiment No. 7 and 8
Aim: Write a program for interfacing button, LED, relay & buzzer as follows
A. When button 1 is pressed relay and buzzer is turned ON and LEDs start chasing from left to
right
B. When button 2 is pressed relay and buzzer is turned OFF and LEDs start chasing from right
to left.

Hardware Requirements: PIC 18F4520 trainer kit, Switch, Relay, Buzzer, LEDs Interfacing.
Software Requirements: MPLAB IDE & C18 Compiler, Embedded C programming.

Theory:
PIC18F4550 is an 8-bit microcontroller of PIC18 family. PIC18F family is based on 16-bit instruction
set architecture. PIC18F4550 consists of 32 KB flash memory, 2 KB SRAM and 256 Bytes EEPROM.
This is a 40 pin PIC Microcontroller consisting of 5 I/O ports (PORTA, PORTB, PORTC, PORTD and
PORTE). PORTB and PORTD have 8 pins to receive/transmit 8-bit I/O data. The remaining ports have
different numbers of pins for I/O data communications. PIC18F4550 can work on different internal and
external clock sources. It can work on a varied range of frequency from 31 KHz to 48 MHz.
PIC18F4550 has four in-built timers. There are various inbuilt peripherals like ADC, comparators etc in
this controller. PIC18F4550 is an advanced microcontroller which is equipped with enhanced
communication protocols like EUSART, SPI, I2C, USB etc.

12
Pin Description:

Pin
Name Description Alternate Function
No.
Master clear
Vpp: programming voltage input
1 MCLR/VPP/RE3 Port E I/O
RE3: I/O pin of PORTE, PIN 3
Pins 3
2 RA0/AN0 AN0: Analog input 0
3 RA1/AN1 AN1: Analog input 1
AN2: Analog input 2
VREF-: A/D reference voltage (low) input.
4 RA2/AN2/VREF-/CVREF
CVREF: Analog comparator reference
output.
AN3: Analog input3
5 RA3/AN3/VREF+ Port A
VREF+: A/D reference voltage (high) input
I/O Pins 0 - 5
T0CKI: Timer0 external clock input.
6 RA4/T0CKI/C1OUT/RCV C1OUT: Comparator 1 output
RCV:External USB transceiver RCV input.
AN4: Analog input 4
SS: SPI slave select input
7 RA5/AN4/SS/HLVDIN/C2OUT
HLDVIN: High/Low-Voltage Detect input.
C2OUT: Comparator 2 output.
AN5: Analog input 5
8 RE0/AN5/CK1SPP
CK1SPP: SPP clock 1 output.
Port E AN6: Analog input 6
9 RE1/AN6/CK2SPP
I/O Pins 0-2 CK2SPP: SPP clock 2 output
AN6: Analog input 7
10 RE2/AN7/OESPP
OESPP : SPP Enabled output
11 Positive supply
VDD
12 Vss Ground
Oscillator pin
13 OSC1/CLKI CLKI: External clock source input
1
Port A CLKO: External clock source output
14 OSC2/CLKO/RA6
I/O Pin 6 OSC2: Oscillator pin 2
T1OSO :Timer1 oscillator output
15 RC0/T1OSO/T13CKI T13CKI: Timer1/Timer3 external clock
input.
Port C
T1OSI: Timer1 oscillator output
I/O Pins 0-2
CCP2:Capture 2 input/Compare 2
16 RC1/T1OSI/CCP2/UOE
output/PWM2 output
UOE: External USB transceiver OE output

13
CCP1: Capture 1 input/Compare 1
output/PWM1 output.
17 RC2/CCP1/P1A
P1A :Enhanced CCP1 PWM output,
channel A.
Internal USB 3.3V voltage regulator output, positive supply
18 VUSB
for the USB transceiver.
19 RD0/SPP0
20 RD1/SPP1 Port D
SPP0-SPP4
I/O Pins 0 -
21 RD2/SPP2 Streaming Parallel Port data
3
22 RD3/SPP3
D-: USB differential minus line
23 RC4/D-/VM (input/output)
Port C VM: External USB transceiver VM input.
I/O Pins 3-4 D+: USB differential plus line
24 RC5/D+/VP (input/output).
VP: External USB transceiver VP input.
TX: EUSART asynchronous transmit.
25 RC6/TX/CK CK: EUSART synchronous clock (see
RX/DT).
Port C
RX: EUSART asynchronous receive.
I/O Pins 6-7
DT: EUSART synchronous data (see
26 RC7/RX/DT/SDO
TX/CK).
SDO: SPI data out.
27 RD4/SPP4 SPP4:Streaming Parallel Port data
SPP5:Streaming Parallel Port data
28 RD5/SPP5/P1B P1B: Enhanced CCP1 PWM output,
channel B
Port D SPP6:Streaming Parallel Port data
29 RD6/SPP6/P1C I/O Pins 4-7 P1C: Enhanced CCP1 PWM output,
channel C
SPP7:Streaming Parallel Port data
30 RD7/SPP7/P1D P1D: Enhanced CCP1 PWM output,
channel D
31 Vss Ground
32 Positive supply
VDD
AN12: Analog input 12.
INT0: External interrupt 0.
FLT0: Enhanced PWM Fault input (ECCP1
33 RB0/AN12/INT0/FLT0/SDI/SDA
module).
Port B SDI: SPI data in.
I /O Pins 1-8 SDA: I2C data I/O.
AN10: Analog input 10.
INT1: External interrupt 1.
34 RB1/AN10/INT1/SCK/SCL
SCK: Synchronous serial clock
input/output for SPI mode.

14
SCL: Synchronous serial clock input/output
for I2C mode.
AN8: Analog input 8.
INT2: External interrupt 2.
35 RB2/AN8/INT2/VMO
VMO: External USB transceiver VMO
output.
AN9: Analog input 9.
CCP2: Capture 2 input/Compare 2
36 RB3/AN9/CCP2/VPO output/PWM2 output.
VPO: External USB transceiver VPO
output.
AN11: Analog input 11.
37 RB4/AN11/KBI0/CSSPP KBI0: Interrupt-on-change pin.
CSSPP: SPP chip select control output.
KBI1: Interrupt-on-change pin.
38 RB5/KBI1/PGM PGM: Low-Voltage ICSP Programming
enable pin.
KBI2: Interrupt-on-change pin.
39 RB6/KBI2/PGC PGC: Low-Voltage ICSP Programming
enable pin.
KBI3: Interrupt-on-change pin.
40 RB7/KBI3/PGD PGD: In-Circuit Debugger and ICSP
programming data pin.

I/O Ports of PIC18F4550:

PIC18F4550 has a total of 35 I/O (input-output) pins which are distributed among 5 Ports. The
following table shows the names and numbers of I/O pins of these 5 ports:

Port Name Number of Pins Pins

PORT A 7 RA0-RA6

PORT B 8 RB0-RB7

PORT C 7 RC0-RC2, RC4-RC7

PORT D 8 RD0-RD7

PORT E 4 RE0-RE3

The 35 I/O pins of PIC18F4550 are also multiplexed with one or more alternative functions of
controller’s various peripherals. In general, when a peripheral is enabled, that pin may not be used as a
general purpose I/O pin. Each Port of a PIC microcontroller corresponds to three 8-bit registers which
should be configured to use the Port for general I/O purpose. These registers are:

1. TRISx: This is a data direction register which sets the direction of each port pin as input or
output.

15
2. PORTx: This register stores the input level of pins (High or Low). When a pin configured as
input, the input signal from external source is read from PORTx register.
3. LATx: This is output latch register. The data which has to be sent to external hardware as
output is stored in LATx register.

Setting a TRISx bit (= 1) will make the corresponding PORTx pin an input . Clearing a TRISx bit (= 0)
will make the corresponding PORTx pin an output
Port Description:

PORTA:
Port A has 7 pins which can be used as both input as well as output pin. The 7th bit is missing from all
the three registers. The input and output given to this port are of 8-bit but the 8th bit is internally
masked.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TRISA - TRISA6 TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 TRISA0

PORTA - RA6 RA5 RA4 RA3 RA2 RA1 RA0

LATA - LATA6 LATA5 LATA4 LATA3 LATA2 LATA1 LATA0

PORTB:
Port B has 8 pins which can all be used for both input and output operation.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TRISB TRISB7 TRISB6 TRISB5 TRISB4 TRISB3 TRISB2 TRISB1 TRISB0

PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0

LATB LATB7 LATB6 LATB5 LATB4 LATB3 LATB2 LATB1 LATB0

PORTC:
Port C has 7 I/O pins. In Port C, Bit 3 is missing in hardware and Pins 4 & 5 can only be used as input
pins. There are no 4th & 5th latch bits in LATC register, so these bits are internally masked during 8-bit
write operation on Port C.

16
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TRISC TRISC7 TRISC6 - - - TRISC2 TRISC1 TRISC0

PORTC RC7 RC6 RC5 RC4 - RC2 RC1 RC0

LATC LATC7 LATC6 - - - LATC2 LATC1 LATC0

PORTD:
Port D has 8 pins which can all be used for both input and output operation.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TRISD TRISD7 TRISD6 TRISD5 TRISD4 TRISD3 TRISD2 TRISD1 TRISD0

PORTD RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0

LATD LATD7 LATD6 LATD5 LATD4 LATD3 LATD2 LATD1 LATD0

PORTE:
Port E has 4 I/O pins. Pin3 can be used as input pin only. RDPU bit is used to enable/disable internal
pull-ups of Port D.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TRISE - - - - - TRISE2 TRISE1 TRISE0

PORTE RPDU - - - RE3 RE2 RE1 RE0

LATE - - - - - LATE2 LATE1 LATE0

I/O configuration:

The TRIS x register is configured to set a pin as input or output. The High value (1) sets a pin as input
pin and Low value (0) sets a pin as output. An easy way to remember this is to consider the
resemblance of 1 with the letter I (for input) and 0 with the letter O (for output).
For example suppose a switch is connected at RB0, RB1 and LEDs are connected to RB2 to RB7 of Port
B. Now the pins 0 & 1 have to be configured as input and pins2 to 7 configured as output. The bit
TRISB0 and TRISB1 is set to 1 to configure RB0 and RB1 as input pins & bits TRISB2 to TRSB7 are set
to 0 to configure RB2 to RB7 as output pins.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

TRISB TRISB7 TRISB6 TRISB5 TRISB4 TRISB3 TRISB2 TRISB1 TRISB0

17
Value 0 0 0 0 0 0 1 1

So the overall value of TRISB register becomes

TRISB= 0000 0011=0x03

MPLAB IDE Software Execition Steps:

1) Open MPLAB IDE software. Create New project in your respctive folder. Do not provide any
extension to the project name. By default software puts .mcp extension.

2) When you will get your project workspace in MPLAB IDE, now create a .c file for your
program. Write the program in that file.

3) Add this .c file to Source file in Workspace.

4) Add linker file rm18f4550.lkr from PIC18F4550_Board folder to Linker Files in workspace.

5) Once .c file is ready, Build the Project. (Follow Project---Build All----Make All steps)

6) If any error is present in .c file. Softeware will mention it in Output window with messege
BUILD FAILED. Lines Numbers containing errors are also mentioned in Output Window.

7) If program is errorfree then Softeware will mention BUILD SUCCESSFUL message means
.hex file is created with project name.

HID BOOTLOADER Execution steps:

1) Run HID BootLoader program from PIC18F4550_Board folder.

2) Connect PIC18F4550_Board to USB port of PC.

3) Now press BOOT and then RESET buttons on PIC18F4550_Board.

4) Now release RESET and BOOT buttons in this sequence only.

5) Check Device attached message on HID Bootloader utility.

6) Now Open .hex file of your project by clicking File option---Import Firmware Image

7) Now program the device.

8) When done, press RESET on PIC18F4550_Board

9) Now connect the interfacing card to proper ports and check the execution of the project.

Result/Oservation:

18
1) When Button1 and Button2 both are open/unpressed, Relay, Buzzer are Off and LEDs shift in
left direction.
2) When Button1 is pressed, Relay, Buzzer are ON and LEDs shift in right direction.
3) When Button2 is pressed, Relay, Buzzer are OFF and LEDs shift in left direction.

Conclusion:
1) TRIS registers are used to define the mode of ports.
2) When port is initialized in output mode, then only LATCH registers are used to send
data.
3) When port is initialized in input mode, then only PORT registers are used to receive the data on
input port.

Program :
/* Main.c file generated by New Project wizard
*
* Created: Thu May 27 2021
* Processor: PIC18F4550
* Compiler: MPLAB XC8
*/

#include <xc.h>

#include <pic18f4550.h> /* Contains PIC18F4550 specifications */

#define Buzzer LATAbits.LATA5 /* Define buzzer pin */


unsigned int count = 0;

void interrupt Timer1_ISR()


{
if(TMR1IF==1)
{
//TMR1=0xCF2C;
TMR1L = 0x20;
TMR1H = 0xD1;
count ++;

if (count >= 1000) //measure upto 1000 ms i.e. 1 seconds


{
Buzzer = ~Buzzer; /* Toggle buzzer pin */
count = 0; //reset count
}
TMR1IF = 0; //timer1 overflow flag to 0
}
}

void main()
{
TRISB=0; /* Set as output port */
TRISAbits.TRISA5 = 0; //set buzzer pin RA5 as output
GIE=1; /* Enable Global Interrupt */

19
PEIE=1; /* Enable Peripheral Interrupt */
TMR1IE=1; /* Enable Timer1 Overflow Interrupt */
TMR1IF=0;

/* Enable 16-bit TMR1 register,no pre-scale,internal clock, timer OFF


*/
T1CON=0x80; /*1:8 prescale*/
TMR1L = 0x20;
TMR1H = 0xD1;
TMR1ON=1; /* Turn ON Timer1 */

while(1);
}

Experiment No. 9

20
Aim: Interface 4X4 keypad to PIC 18F4520 and write a program in Embedded C to display key
pressed
on LCD or on hyper-terminal.

Hardware Requirements: PIC 18F4520 trainer kit, LCD, 4X4 keypad matrix.
Software Requirements: MPLAB IDE & C18 Compiler, Embedded C programming.

Theory:
4X4 Matrix Keypad interfacing with PIC microcontroller:

Matrix keypads are very useful when designing certain systems which needs user input. These keypads
are constructed by arranging push button switches in rows and columns as shown in Fig.1. Scanning
keypad to detect pressed keys involves several steps:

1. Supply logic 0 (0V or GND) to all 4 keypad row wires named R1, R2, R3 and R4 in schematic
diagram.(Assume that no key is pressed and since all columns has 1k pull down resisters
connected as in schematic diagram.)
2. Check all column line status. If all are at logic HIGH means no key press. It will wait it key
press is occurred. One can use PORT B – change interrupt feature. If any key press occurs
microcontroller will execute ISR. This ISR

a) Ensures that keypress is not erroneous due to spike noise


b) Wait for 20ms to prevent the same key press for being interpreted as multiple key presses.

3. To detect which row has key press microcontroller grounds one roe at a time, reading the
columns each time. If columns are high, this means the key press cannot belong to that row;
therefore it grounds the next row and continues until it finds the row the key press belongs to.

21
Upon finding row that the key press belongs to, it sets up ASCII value or scan code to identify
the key.

MPLAB IDE Software Execition Steps:


1) Open MPLAB IDE software. Create New project in your respctive folder. Do not provide any
extension to the project name. By default software puts .mcp extension.
2) When you will get your project workspace in MPLAB IDE, now create a .c file for your
program. Write the program in that file.
3) Add this .c file to Source file in Workspace.
4) Add linker file rm18f4550.lkr from PIC18F4550_Board folder to Linker Files in workspace.
5) Once .c file is ready, Build the Project. (Follow Project---Build All----Make All steps)
6) If any error is present in .c file. Softeware will mention it in Output window with messege
BUILD FAILED. Lines Numbers containing errors are also mentioned in Output Window.
7) If program is errorfree then Softeware will mention BUILD SUCCESSFUL message means
.hex file is created with project name.

HID BOOTLOADER Execution steps:


1) Run HID BootLoader program from PIC18F4550_Board folder.
2) Connect PIC18F4550_Board to USB port of PC.
3) Now press BOOT and then RESET buttons on PIC18F4550_Board.
4) Now release RESET and BOOT buttons in this sequence only.
5) Check Device attached message on HID Bootloader utility.
6) Now Open .hex file of your project by clicking File option---Import Firmware Image
7) Now program the device.
8) When done, press RESET on PIC18F4550_Board
9) Now connect the interfacing card to proper ports and check the execution of the project.

Result:
We studied the interfacing of 4X4 keyboard and displayed the key on LCD.

Conclusion:
1) Always Row lines are in output mode and column lines are in input mode.
2) User can use Port-B change of interrupt feature for interfacing keypad.
Program

/* Main.c file generated by New Project wizard


*
* Created: Wed May 26 2021
* Processor: PIC18F4550
* Compiler: MPLAB XC8
*/

#include <xc.h>

#include <p18f4550.h>

22
#define LCD_EN LATAbits.LA1
#define LCD_RS LATAbits.LA0
#define LCDPORT LATB

void lcd_delay(unsigned int time)


{
unsigned int i , j ;

for(i = 0; i < time; i++)


{
for(j=0;j<100;j++);
}
}

void SendInstruction(unsigned char command)


{
LCD_RS = 0; // RS low : Instruction
LCDPORT = command;
LCD_EN = 1; // EN High
lcd_delay(10);
LCD_EN = 0; // EN Low; command sampled at EN falling edge
lcd_delay(10);
}

void SendData(unsigned char lcddata)


{
LCD_RS = 1; // RS HIGH : DATA
LCDPORT = lcddata;
LCD_EN = 1; // EN High
lcd_delay(10);
LCD_EN = 0; // EN Low; data sampled at EN falling edge
lcd_delay(10);
}

void InitLCD(void)
{
ADCON1 = 0x0F;
TRISB = 0x00; //set data port as output
TRISAbits.RA0 = 0; //RS pin
TRISAbits.RA1 = 0; // EN pin

SendInstruction(0x38); //8 bit mode, 2 line,5x7 dots


SendInstruction(0x06); // entry mode
SendInstruction(0x0C); //Display ON cursor OFF
SendInstruction(0x01); //Clear display
SendInstruction(0x80); //set address to 1st line

}
/**************************************************************************
******************************************/

23
unsigned char *String1 = "Microembedded";
unsigned char *String2 = "PIC-18F Board";

void main(void)
{
ADCON1 = 0x0F;
TRISB = 0x00; //set data port as output
TRISAbits.RA0 = 0; //RS pin
TRISAbits.RA1 = 0; // EN pin

SendInstruction(0x38); //8 bit mode, 2 line,5x7 dots


SendInstruction(0x06); // entry mode
SendInstruction(0x0C); //Display ON cursor OFF
SendInstruction(0x01); //Clear display
SendInstruction(0x80); //set address to 1st line

while(*String1)
{
SendData(*String1);
String1++;
}

SendInstruction(0xC0); //set address to 2nd line


while(*String2)
{
SendData(*String2);
String2++;
}

while(1);

Experiment No. 10

24
Aim: Write a program for Generation of PWM signal for DC Motor control.

Hardware Requirements: PIC 18F4520 trainer kit, DC motor interfacing card.

Software Requirements: MPLAB IDE & C18 Compiler, Embedded C programming.

Theory:

DC Motors

A direct current (DC) motor is widely used device that translates electrical pulses in to
mechanical movement I the DC motors there are + and – leads. Connecting them to a
DC voltage source moves the motor in one direction. By reversing the polarity, the DC
motor will move in opposite direction.

DC Motor rotation

Pulse width Modulation (PWM)

The speed of Dc motor depends on three factors:

i. load

ii. Voltage

iii. Current

25
For a given fixed load we can maintain a steady speed by using a method called Pulse
width Modulation (PWM).By changing the width of pulse applied to DC motor we can
increase or decrease the amount of power provided to motor, there by increasing or
decreasing the speed of motor.

CCP in PWM MODE:

26
PWM PERIOD:

The output pulse period (T) is determined by the PR2 register of the timer TMR2. The
PWM period can be calculated using the following equation:

PWM Period = (PR2 +1) * 4Tosc * TMR2 Prescaler Value.

If the PWM period (T) is known, then it is easy to determine the signal frequency F
because these two values are related by equation F=1/T.

PWM DUTY CYCLE:

The PWM duty cycle is specified by using in total of 10 bits: eight MSbs of the
CCPR1L register and two additional LSbs of the CCP1CON register (DC1B1 and
DC1B0). The result is a 10-bit number contained in the formula:

Pulse Width = (CCPR1L, DC1B1, DC1B0) * Tosc * TMR2 Prescale Value

Registers associated with PWM programming

CCP high and low register

CCP1 Control register

Timer2 Control register

PIR1 register

27
CCP high and low register

28
29
MPLAB IDE Software Execition Steps:

8) Open MPLAB IDE software. Create New project in your respctive folder. Do not provide any
extension to the project name. By default software puts .mcp extension.

9) When you will get your project workspace in MPLAB IDE, now create a .c file for your
program. Write the program in that file.

10) Add this .c file to Source file in Workspace.

11) Add linker file rm18f4550.lkr from PIC18F4550_Board folder to Linker Files in workspace.

12) Once .c file is ready, Build the Project. (Follow Project---Build All----Make All steps)

13) If any error is present in .c file. Softeware will mention it in Output window with messege
BUILD FAILED. Lines Numbers containing errors are also mentioned in Output Window.

14) If program is errorfree then Softeware will mention BUILD SUCCESSFUL message means
.hex file is created with project name.

HID BOOTLOADER Execution steps:

10) Run HID BootLoader program from PIC18F4550_Board folder.

11) Connect PIC18F4550_Board to USB port of PC.

12) Now press BOOT and then RESET buttons on PIC18F4550_Board.

13) Now release RESET and BOOT buttons in this sequence only.

14) Check Device attached message on HID Bootloader utility.

15) Now Open .hex file of your project by clicking File option---Import Firmware Image

16) Now program the device.

17) When done, press RESET on PIC18F4550_Board

18) Now connect the interfacing card to proper ports and check the execution of the project.

Conclusion:Thus we have interfaced DC motor with PIC Microcontroller

30
Interfacing Diagram:

31
Program:
/* Main.c file generated by New Project wizard
*
* Created: Thu May 27 2021
* Processor: PIC18F4550
* Compiler: MPLAB XC8
*/

#include <xc.h>

/* Calculations
* Fosc = 48MHz
*
* PWM Period = [(PR2) + 1] * 4 * TMR2 Prescale Value / Fosc
* PWM Period = 200us
* TMR2 Prescale = 16
* Hence, PR2 = 149 or 0x95
*
* Duty Cycle = 10% of 200us
* Duty Cycle = 20us
* Duty Cycle = (CCPR1L:CCP1CON<5:4>) * TMR2 Prescale Value / Fosc
* CCP1CON<5:4> = <1:1>
* Hence, CCPR1L = 15 or 0x0F
*/

#include<p18f4550.h>

unsigned char count=0;


bit TIMER,SPEED_UP;

void timer2Init(void)
{
T2CON = 0b00000010; //Prescalar = 16; Timer2 OFF
PR2 = 0x95; //Period Register
}

void delay(unsigned int time)


{
unsigned int i,j;
for(i=0;i<time;i++)
for(j=0;j<1000;j++);
}

void main(void)
{
unsigned int i;
TRISCbits.TRISC1 = 0; //RC1 pin as output
TRISCbits.TRISC2 = 0; //CCP1 pin as output
LATCbits.LATC1 = 0;

32
CCP1CON = 0b00111100; //Select PWM mode; Duty cycle LSB
CCP1CON<4:5> = <1:1>
CCPR1L = 0x0F; //Duty cycle 10%
timer2Init(); //Initialise Timer2
TMR2ON = 1; //Timer2 ON

while(1) //Loop forever


{
for(i=15;i<150;i++)
{
CCPR1L = i;
delay(100);
}
for(i=150;i>15;i--)
{
CCPR1L = i;
delay(100);
}
}
}

33
Experiment No. 11

Aim: Write a program in Embedded C to interface serial port with PC for both
side Communications.

Hardware Requirements: PIC 18F4550 trainer kit

Software Requirements: MPLAB IDE & C18 Compiler, Embedded C programming.

Theory:
The USART(universal synchronous asynchronous receiver transmitter) in PIC18F has both the
synchronous and asynchronous feature. The synchronous mode can be used to transfer data between the
PIC and external peripherals such as ADC and EEPROMs. The asynchronous mode is used to connect
PIC18F system with IBM PC serial port for full duplex serial data transfer.
These are the registers associated with the USART module:

1) SPBRG: Baud Rate Generator Register Low Byte


2) TXREG: USART Transmit Register
3) RCREG: EUSART Receive Register
4) TXSTA: Transmit Status and Control
5) RCSTA: Receive Status and Control
6) PIR1: Peripheral interrupt request register1

1) SPBREG register and Baud Rate in PIC18:


For a given crystal frequency the value loaded in SPBRG decides the baud rate. Relation between
baud rate and oscillator frequency is given below:
Desired Baud Rate = Fosc / (64X+64) = Fosc / 64(X+1)
Where X is the value we load into SPBGR register.
If Fosc=20MHz then
Desired Baud Rate = 20MHz / (64X+64) = 20MHz / 64(X+1)
Desired Baud Rate = 312500/(X+1)
To get X value for different baud rate we can solve as
X= (Desired baud rate/312500) -1

34
TXSTA: TRANSMIT STATUS AND CONTROL REGISTER
CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D

bit 7 CSRC: Clock Source Select bit


Asynchronous mode:Don’t care.
Synchronous mode:
1 = Master mode (clock generated internally from BRG)
0 = Slave mode (clock from external source)
bit 6 TX9: 9-Bit Transmit Enable bit
1 = Selects 9-bit transmission 0 = Selects 8-bit transmission
bit 5 TXEN: Transmit Enable bit(1)
1 = Transmit enabled 0 = Transmit disabled
bit 4 SYNC: EUSART Mode Select bit
1 = Synchronous mode 0 = Asynchronous mode
bit 3 SENDB: Send Break Character bit
Asynchronous mode:
1 = Send Sync Break on next transmission (cleared by hardware upon completion)
0 = Sync Break transmission completed
Synchronous mode: Don’t care.
bit 2 BRGH: High Baud Rate Select bit
Asynchronous mode:
1 = High speed 0 = Low speed
Synchronous mode: Unused in this mode.
bit 1 TRMT: Transmit Shift Register Status bit
1 = TSR empty 0 = TSR full
bit 0 TX9D: 9th bit of Transmit Data
Can be address/data bit or a parity bit.
(Note 1: SREN/CREN overrides TXEN in Sync mode with the exception that SREN has
no effect in Synchronous Slave mode.)

RCSTA: RECEIVE STATUS AND CONTROL REGISTER

SPEN RX9 SREN CREN ADDEN FERR OERR RX9D


bit 7 SPEN: Serial Port Enable bit
1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins)
0 = Serial port disabled (held in Reset)
bit 6 RX9: 9-Bit Receive Enable bit
1 = Selects 9-bit reception 0 = Selects 8-bit reception
bit 5 SREN: Single Receive Enable bit

35
Asynchronous mode: Don’t care.
Synchronous mode – Master:
1 = Enables single receive 0 = Disables single receive
This bit is cleared after reception is complete.
Synchronous mode – Slave:Don’t care.

bit 4 CREN: Continuous Receive Enable bit


Asynchronous mode:
1 = Enables receiver
0 = Disables receiver
Synchronous mode:
1 = Enables continuous receive until enable bit CREN is cleared (CREN overrides
SREN)
0 = Disables continuous receive
bit 3 ADDEN: Address Detect Enable bit
Asynchronous mode 9-bit (RX9 = 1):
1 = Enables address detection, enables interrupt and loads the receive buffer when
RSR<8> is set
0 = Disables address detection, all bytes are received and ninth bit can be used as
parity bit
Asynchronous mode 9-bit (RX9 = 0):Don’t care.
bit 2 FERR: Framing Error bit
1 = Framing error (can be updated by reading RCREG register and receiving next
valid byte)
0 = No framing error
bit 1 OERR: Overrun Error bit
1 = Overrun error (can be cleared by clearing bit CREN)
0 = No overrun error
bit 0 RX9D: 9th bit of Received Data
This can be address/data bit or a parity bit and must be calculated by user
firmware.

36
PIR1(Peripheral interrupt request register 1):
Two of the PIR1 register bits are used by UART. They are TXIF( transmit interrupt flag)
and RXIF(receive interrupt flag). We monitor TXIF flag to make sure that all the bits are
transmitted before we write another byte into TXREG. We monitor RCIF flag to see if a
byte data has come or not.

Steps in Programming PIC18 to transfer data serially:


1) The TXSTA is loaded with 20H indicating asynchronous 8-bit mode, low baud
rate and transmit enabled.
2) Make TX pin on PORTC(RC6) an output for transmitting data.
3) SPBRG and SPBRGH are loaded with appropriate values for baud rate.
4) SPEN bit in RCSTA is set high to enable serial port of PIC18.
5) The character byte to be transmitted is loaded in TXREG register
6) Monitor the TXIF bit of the PIR1 register to make sure UART is ready for next
byte.
7) To send next character go to step 5.

Steps in Programming PIC18 to receive data serially:


1) The RCSTA is loaded with 90H to enable continuous receive 8-bit data.
2) The TXSTA is loaded with 00H to choose the low baud rate option.
3) SPBRG and SPBRGH are loaded with appropriate values for baud rate
4) Make RX pin on PORTC(RC7) an input for receiving data.

37
5) Monitor the RCIF bit of the PIR1 register to make sure UART has received entire
8-bit data.
6) To receive next character go to step 5.

There are two ways to increase the baud rate


1) Use a higher- frequency crystal:
As crystal is fixed so it is not a feasible solution.
2) Change a bit BRGH=0 in the TXSTA register:
This is the software way to quadruple the baud rate of the PIC18 while crystal
frequency is same.
When BRGH=0, the PIC18 divides Fosc/4 by 16 once more and uses this
frequency for UART to set the baud rate.
When BRGH=1, the PIC18 divides Fosc/4 by 4 once more and uses this
frequency for UART to set the baud rate.
Thus by making BRGH=1, user can quadruple the baud rate.

38
Conclusion: Thus we have done PC to PC communication using serial communication

Program:

/* Main.c file generated by New Project wizard


*
* Created: Thu May 27 2021
* Processor: PIC18F4550
* Compiler: MPLAB XC8
*/

#include <xc.h>
/*Baud Rate GENERATION
* n => required baudrate
* BRGH = 0
* SPBRG = (Fosc / (64 * n)) -1
* For 9600 baudrate, SPBRG ~=77
*/

#include<p18F4550.h>
#include<stdio.h>
#define Fosc 48000000UL

void InitUART(unsigned int baudrate)


{
TRISCbits.RC6 = 0; //TX pin set as output
TRISCbits.RC7 = 1; //RX pin set as input

SPBRG = (unsigned char)(((Fosc /64)/baudrate)-1);


BAUDCON = 0b00000000; //Non-inverted data; 8-bit
baudrate generator

TXSTA = 0b00100000; //Asynchronous 8-bit; Transmit


enabled; Low speed baudrate select
RCSTA = 0b10010000; //Serial port enabled; 8-bit
data; single receive enabled
}

void SendChar(unsigned char data)


{
while(TXSTAbits.TRMT == 0); //Wait while transmit register
is empty

TXREG = data; //Transmit data


}

void putch(unsigned char data)


{
SendChar(data);
}

unsigned char GetChar(void)

39
{
while(!PIR1bits.RCIF); //Wait till receive buffer
becomes full
return RCREG; //Returned received data
}

void main(void)
{
InitUART(9600);

printf("\r\nHello MicroPIC-18F: Enter any Key from Keyboard\r\n");

while(1)
{
printf("%c! ",GetChar()); //Receive character from PC
and echo back
}

while(1);
}

40

You might also like