PSDL Final Manual Updated (Footer21-22)
PSDL Final Manual Updated (Footer21-22)
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.
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.
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.
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.
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;
5
How to see the Result
6
Experiment No. 2 : Write an Embedded C program to add array of n numbers.
*/
#include <stdio.h>
#include <stdlib.h>
#include <pic18f4550.h>
void main(void) {
int i,sum,n;
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
#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
}
}
8
II) Memory Exchange
/*
* File: mem_xchg.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <pic18f4550.h>
void main(void) {
int temp,i;
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>
result = 0;
num1 = 0x23;
num2 = 0x10;
TRISB =0;
PORTB = result;
10
Experiment No. 5 : . Write an Embedded C program for sorting the numbers in ascending
and descending order.
#include <stdio.h>
#include <stdlib.h>
#include <pic18f4550.h>
void main(void) {
int i,j,temp;
int num_asc[] = {10,2,5,1,6};
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.
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 A 7 RA0-RA6
PORT B 8 RB0-RB7
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.
PORTB:
Port B has 8 pins which can all be used for both input and output operation.
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
PORTD:
Port D has 8 pins which can all be used for both input and output operation.
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.
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.
17
Value 0 0 0 0 0 0 1 1
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.
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.
6) Now Open .hex file of your project by clicking File option---Import Firmware Image
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>
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;
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
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.
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
#include <xc.h>
#include <p18f4550.h>
22
#define LCD_EN LATAbits.LA1
#define LCD_RS LATAbits.LA0
#define LCDPORT LATB
void InitLCD(void)
{
ADCON1 = 0x0F;
TRISB = 0x00; //set data port as output
TRISAbits.RA0 = 0; //RS pin
TRISAbits.RA1 = 0; // EN pin
}
/**************************************************************************
******************************************/
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
while(*String1)
{
SendData(*String1);
String1++;
}
while(1);
Experiment No. 10
24
Aim: Write a program for Generation of PWM signal for DC Motor control.
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
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.
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:
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.
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:
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.
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.
13) Now release RESET and BOOT buttons in this sequence only.
15) Now Open .hex file of your project by clicking File option---Import Firmware Image
18) Now connect the interfacing card to proper ports and check the execution of the project.
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>
void timer2Init(void)
{
T2CON = 0b00000010; //Prescalar = 16; Timer2 OFF
PR2 = 0x95; //Period Register
}
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
33
Experiment No. 11
Aim: Write a program in Embedded C to interface serial port with PC for both
side Communications.
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:
34
TXSTA: TRANSMIT STATUS AND CONTROL REGISTER
CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D
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.
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.
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.
38
Conclusion: Thus we have done PC to PC communication using serial communication
Program:
#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
39
{
while(!PIR1bits.RCIF); //Wait till receive buffer
becomes full
return RCREG; //Returned received data
}
void main(void)
{
InitUART(9600);
while(1)
{
printf("%c! ",GetChar()); //Receive character from PC
and echo back
}
while(1);
}
40