You are on page 1of 29

LAB.

1+2
Blinking LED using PIC Microcontroller

MikroC is the best compiler for beginners as it contains built in functions for most of the
commonly used tasks. But MikroC is less efficient and the hex file generated will be large size
compared to other compilers. So it is suggested to use Hi-Tech C compiler by Microchip after
you get familiar with microcontrollers. Note that, Hi-Tech C is a bit difficult compared to
MikroC as there is no built in functions.

Getting Started with MikroC Pro

You can download a trial version of mikroC form mikroElectronika . Trial Version is limited to
2k of program words and is sufficient for most of our applications.

 Download and Install MikroC Pro


 Create a Folder for this project in any of your drives
 Open microC Pro For PIC
 Click on Project >> New Project

 Click Next
Project Settings – New Project Wizard

 Enter Project name, path (created folder path), clock frequency, microcontroller and
click Next. Clock Frequency is the frequency of oscillator used with microcontroller.
Here we use PIC 18F45K22 microcontroller with 8MHz crystal.
 Here you can add your subprogram files or user defined header files in large projects.
Hence we are dealing with simple LED Blinking in this tutorial, ignore it and click Next.
 Here you can add MikroC’s built in libraries such as UART, PWM, LCD etc… You may
include All Libraries or include None. If you select None, then you can selectively
include required libraries later. Then click Next.
 Click Finish, to complete the New Project Wizard.
 Then you will see the editor, where you can enter the MikroC Code.

MikroC Programming

Before going to the programming you should understand the following things.

 Output pins of a PIC Microcontroller is divided in to different PORTS containing a group


of GPIO (General Purpose Input Output Pins) pins.
 In 16F PIC Microcontrollers, there are two registers associated with a port, TRIS and
PORT. eg: TRISB, PORTB, TRISC, PORTC
 TRIS stands for Tri-State, which determines the direction of each GPIO pin. Logic 1 at a
particular bit of TRIS register makes the corresponding pin Input and Logic 0 at a
particular bit of TRIS register makes the corresponding pin Output. An Input pin of PIC
Microcontroller have very high input impedance, thus it may said to be in Hi-Impedance
state.
 PORT register is used to read data from or write data to GPIO pins. Logic 1 at a
particular bit of PORT register makes the corresponding pin at Logic High (VDD) and
Logic 0 at a particular bit of PORT register makes the corresponding pin at Logic Low
(VSS) if that pin is an Output pin (TRIS bit is 0).
 PORT register can be used to read digital data from an Input pin. Logic 1 indicates the
pin is at Logic High and Logic 0 indicates that the pin is at Logic Low.

 You can write to PORT and TRIS register entirely or bit by bit.

Writing Bit by Bit :

TRISC.F0 = 1; //Makes 0th bit of PORTC Input

TRISC.F5 = 0; //Makes 5th bit of PORTC Output

PORTB.F3 = 1; //Makes 3ed bit of PORTB at Logic High

PORTB.F7 = 0; //Makes 7th bit of PORTB at Logic Low


Writing Entire Register

You should be familiar with following C Programming concepts.

 A number with a prefix ‘0b’ indicates a binary number.


 A number with a prefix ‘0’ indicates an octal number.
 A number with a prefix ‘0x’ indicates a hexadecimal number.
 A number without prefix is a decimal number.

Let’s see some examples…

Decimal Binary Octal Hexadecimal

0 0b00000000 00 0x00

1 0b00000001 01 0x01

128 0b10000000 0200 0x80

255 0b11111111 0377 0xFF

PORTB = 0xFF; //Makes all pins of PORTB Logic High

TRISC = 0x00; //Makes all pins of TRISC Output

PORTD = 128; //Makes 7th bit of PORTD Logic High


MikroC Code – Blinking an LED

The following program blinks an LED with a delay of 1 second.

void main()

{ ANSELB=0; //USE PORTB as Digital I/O

TRISB.F0 = 0; //Makes PORTB0 or RB0 Output Pin

while(1) //Infinite Loop

PORTB.F0 = 1; //LED ON

Delay_ms(1000); //1 Second Delay

PORTB.F0 = 0; //LED OFF

Delay_ms(1000); //1 Second Delay

Note : Delay_ms(const unsigned long a) is a built in function of MikroC Pro which provides a
delay of ‘a’ milliseconds. The variable ‘a’ must be a constant of type unsigned long integer.

 Enter the above MikroC code

Enter Your Code Here – MikroC Pro

 Save it
 Then Compile it. Click Build >> Build (or Ctrl+F9)
A hex file will be generated in your Project Folder. You need to write this file to microcontroller
using a programmer.

Circuit Diagram:

Use Proteus to draw the connection.

VDD and VSS of PIC Microcontroller is connected to +5V and GND respectively to provide necessary
power for the operation of the microcontroller. 8MHz crystal is used to provide necessary clock for the
microcontroller. 22pF capacitors stabilizes the oscillations of the crystal. LED is connected to the 0th bit of
PORTB and a 470Ω resistor is connected in series to limit the current through the LED.
Input Using Push Button:

Suppose push button switch is connected to the first bit of PORT D (RD0) which is configured
as an input pin. Which is connected to a pull up resistor such that this pin is at Vcc potential
when the switch is not pressed. When the switch is pressed this pin RD0 will be grounded. The
LED is connected to the first bit of PORT B (RB0) and a resistor is connected in series with it to
limit the current.

MikroC program:

void main()

ANSELD=0;

ANSELB=0;

TRISD.F0 = 1; //Configure 1st bit of PORTD as input

TRISB.F0 = 0; //Configure 1st bit of PORTB as output

PORTB.F0 = 0; //LED OFF

While(1)

if(PORTD.F0 == 0) //If the switch is pressed

PORTB.F0 = 1; //LED ON

Delay_ms(1000); //1 Second Delay

PORTB.F0 = 0; //LED OFF

}}}
LAB. Tasks:

1- Implement the previous codes and connections

2- Modify the code and connection to perform 8bits up counter with 1-sec
delay between each count.

3- Write a program needed to control one push buttons connected to PORTD


(D0 Pin) and eight LEDs to PORTC then do the following:

- Initialize the LEDs to 0.

- Each time you press the button the LEDs must count up by one.

4- Apply all previous projects on Easy PIC board. See User guide page 13
programming software “how to download the hex-file to the PIC”
LAB.3
Multiplexing of Seven Segment Displays with PIC Microcontroller

When a Seven Segment Display is interface with PIC Microcontroller it needs minimum 7 pins
to display a value. But real time applications like Digital Clock, Calculator, Digital Watch
requires 3-6 seven segment displays. Lets assume that we need 6 digit display, ie we need 7
segment * 6 Display = 42 pins. Thus we actually need Microcontroller with 42 output pins. This
is waste and not economical to use lot of pins of a Microcontroller just for display.

The simplest way to drive Seven Segment Display is by using a driver or decoder and are
available for up to 4 displays. Alternatively we can drive more than one Seven Segment Display
by using a technique called ‘Multiplexing’. This technique is based on the principle of
Persistence of Vision of our eyes. If the frames change at a rate of 25 ( or more) frames per
second, human eye can’t detect that visual change. Each display is turned on above this rate and
our eyes will think that the display is turned on for whole the time.

 User guide page 27 shows hardware connection details.

Code to display number “10” using Seven SegmentDisplays:

void main() {
trisa=0;
trisd=0;
ansela=0;
anseld=0;
while(1)
{
porta=1;
portd=0b00111111;
delay_ms(10);
porta=2;
portd=0b00000110;
delay_ms(10);
}}
Counter code using push button
void main() {
int i=0;
unsigned char x[]={0b00111111,0b00000110,0b01011011,…….};
// Complete numbers using Mikroc seven segment editor. From Tools menu
trisa=0;
trisd=0;
porta=1;
trisc=1;
anselc=0;
portd=x[0];

while(1)

{
if(portc.f0==1)
{i++;
portd=x[i];
delay_ms(30);
while(portc.f0==1){}
delay_ms(30);}
}}
LAB. Tasks:

1- Implement the previous codes

2- Write the needed code to display number “153”.

3- Using two push buttons and one seven-segment display write the needed
code to do the following:

- Initialize seven-segment display to display 0.

If the first push button is pressed once then the seven-segment display will
count up, else if the second push button is pressed once then the seven-
segment display will count down
LAB. 4
LCD interfacing with PIC Microcontroller

A PIC Microcontroller can be easily made to communicate with LCD by using the built in
Libraries of MikroC. Interfacing between PIC and LCD can be 4-bit or 8-bit. The difference
between 4-bit and 8-bit is how data are send to the LCD. In the 8-bit mode to write an 8-
bit character to the LCD module, ASCII data is send through the data lines DB0- DB7 and data
strobe is given through the E line.

But 4-bit mode uses only 4 data lines. In this mode the 8-bit ASCII data is divided into 2 parts
which are send sequentially through data lines DB4 – DB7 with its own data strobe through the
E line. The idea of 4-bit communication is to save as much pins that used to interface with LCD.
The 4-bit communication is a bit slower when compared to 8-bit. The speed difference is only
minimal, as LCDs are slow speed devices the tiny speed difference between these two modes is
not significant. Thus the 4-bit mode data transmission is most commonly used.

 User guide page 24 shows hardware connection details.

MikroC Pro LCD Library

MikroC Pro provides built in libraries for interfacing LCDs with HD44780 compliant controllers
using 4 bit mode data transmission.

Defining LCD Connections

For the proper functioning of the LCD library, you must define, how the pins of LCD are
connected to pic microcontroller as given next.
// LCD module connections

sbit LCD_RS at RB2_bit;

sbit LCD_EN at RB3_bit;

sbit LCD_D4 at RB4_bit;

sbit LCD_D5 at RB5_bit;

sbit LCD_D6 at RB6_bit;

sbit LCD_D7 at RB7_bit;

sbit LCD_RS_Direction at TRISB2_bit;

sbit LCD_EN_Direction at TRISB3_bit;

sbit LCD_D4_Direction at TRISB4_bit;

sbit LCD_D5_Direction at TRISB5_bit;

sbit LCD_D6_Direction at TRISB6_bit;

sbit LCD_D7_Direction at TRISB7_bit;

// End LCD module connections

The above definitions tell the compiler, how LCD is connected to the microcontroller. The two set of
definitions are used to provide Data (PORT) and Direction (TRIS) registers.

Library Functions

1- Lcd_Init

Prototype : void Lcd_Init();

This function initializes the LCD module connected to the above defined pins of the PIC
Microcontroller.
2- Lcd_Out

Prototype : void Lcd_Out(char row, char column, char *text);

This functions prints the text (string) in a particular row and column.

3- Lcd_Out_Cp

Prototype : void Lcd_Out_Cp(char *text);

This function prints the text (string) in the current cursor position. When we write data to LCD
Screen, it automatically increments the cursor position.

4- Lcd_Chr

Prototype : void Lcd_Chr(char row, char column, char out_char);

It prints the character (out_char) in the specified row and column of the LCD Screen.

5- Lcd_Chr_Cp

Prototype : void Lcd_Chr_Cp(char out_char);

It prints the character (out_char) in the current cursor position.

6- Lcd_Cmd

Prototype : void Lcd_Cmd(char out_char);


This function is used to send commands to LCD. You can use any one of the following constants
as command.

 _LCD_TURN_ON – Turns ON the LCD Display.


 _LCD_TURN_OFF – Turns OFF the LCD Display.
 _LCD_FIRST_ROW – Moves the cursor to the first row.
 _LCD_SECOND_ROW – Moves the cursor to the the second row.
 _LCD_THIRD_ROW – Moves the cursor to the third row.
 _LCD_FOURTH_ROW – Moves the cursor to the fourth row.
 _LCD_CLEAR – Clears the LCD Display.
 _LCD_CURSOR_OFF – Turns ON the cursor.
 _LCD_UNDERLINE_ON – Turns ON the cursor underline.
 _LCD_BLINK_CURSOR_ON – Turns ON the cursor blink.
 _LCD_MOVE_CURSOR_LEFT – Moves cursor LEFT without changing the data.
 _LCD_MOVE_CURSOR_RIGHT – Moves cursor RIGHT without changing the data.
 _LCD_SHIFT_LEFT – Shifts the display left without changing the data in the display
RAM.
 _LCD_SHIFT_RIGHT – Shifts the display right without changing the data in the display
RAM.
 _LCD_RETURN_HOME – Returns the cursor and shifted display to Home position.
LCD Interfacing MikroC Pro Code

// LCD module connections

// Copy the first lines from: help index write LCD at the end of page copy from the written program"

sbit LCD_RS at RB2_bit;

sbit LCD_EN at RB3_bit;

sbit LCD_D4 at RB4_bit;

sbit LCD_D5 at RB5_bit;

sbit LCD_D6 at RB6_bit;

sbit LCD_D7 at RB7_bit;

sbit LCD_RS_Direction at TRISB2_bit;

sbit LCD_EN_Direction at TRISB3_bit;

sbit LCD_D4_Direction at TRISB4_bit;

sbit LCD_D5_Direction at TRISB5_bit;

sbit LCD_D6_Direction at TRISB6_bit;

sbit LCD_D7_Direction at TRISB7_bit;

// End LCD module connections

void main()

{ ANSELB=0;

Lcd_Init(); // Initialize LCD

Lcd_Cmd(_LCD_CLEAR); // Clear display

Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off

Lcd_Out(1,1,"Hello World");//Write text'Hello World' in first row

}
LAB. Tasks:

1- Implement the previous code and connection


2- Write the needed code to display any text and move it as news bar.

3- Using one push button and one LCD do the following:

- Initialize LCD to display 0.

- Each time the push button is pressed the LCD must count up by one.

- Hint: Form Mikroc help see IntToStr function


LAB. 5

Piezo Buzzer

Using buzzer to generate sounds and music. User guide page 32 shows hardware connection details.
Assume sound as square wave which you can modify its frequency and duty cycle to change the
sound. Next code shows how to generate beep sound each time a push button is pressed:

void main() {

trisc=0; //output port

portc=0;

anselc=0;

trisb=1;

anselb=0;

while(1)

{if(portb.f0==1)

{portc=0;

delay_us(1916);

portc=255;

delay_us(1916);}}
}
LAB. Tasks:
1- Implement the previous code and connection
2- In the previous code calculate the sound frequency and duty cycle.
3- Modify the code using the same frequency with duty cycle 75%. Note the
difference.
4- Write the needed code using eight push buttons as piano.
5- Rewrite the previous codes using MikroC function “Sound”. See Mikroc
help.
Sound_Init(&PORTC, 2);
Sound_Play(880, 1000); // Play sound at 880Hz for 1 second
LAB . 6

Interfacing DC Motor with PIC Microcontroller

We can’t drive a DC Motor (depends) directly with a Microcontroller, as DC Motors requires


high current and high voltage than a Microcontroller can handle. Microcontrollers usually
operates at +5 or +3.3V supply and it I/O pin can provide only up to 25mA current. Commonly
used DC Motors requires 12V supply and 300mA current, moreover interfacing DC Motors
directly with Microcontrollers may affect the working of Microcontroller due to the Back EMF
of the DC Motor. Thus it is clear that, it not a good idea to interface DC Motor directly with
Microcontrollers.

The solution to above problems is to use H-bridge circuit. It is a special circuit, by using the 4
switches we can control the direction of DC Motor. Depending upon our power requirements we
can make our own H-bridge using Transistors/MOSFETs as switches. It is better to use ready
made ICs, instead of making our own H-bridge.

DC Motor and L293D:


L293D and L293 are two such ICs. These are dual H-bridge motor drivers, ie by using one IC we
can control two DC Motors in both clock wise and counter clockwise directions. The L293D can
provide bidirectional drive currents of up to 600-mA at voltages from 4.5 V to 36 V while L293
can provide up to 1A at same voltages. Both ICs are designed to drive inductive loads such as dc
motors, bipolar stepping motors, relays and solenoids as well as other high-current or high-
voltage loads in positive-supply applications. All inputs of these ICs are TTL compatible and
output clamp diodes for inductive transient suppression are also provided internally. These
diodes protect our circuit from the Back EMF of DC Motor.
In both ICs, drivers are enabled in pairs, with drivers 1 and 2 are enabled by a high input to
1,2EN and drivers 3 and 4 are enabled by a high input to 3,4EN. When drivers are enabled,
their outputs will be active and in phase with their inputs. When drivers are disabled, their
outputs will be off and will be in the high-impedance state.
PIN Diagram of L293D
Function Table of L293D

Interfacing with PIC Microcontroller Circuit Diagram:

interfacing DC Motor with PIC Microcontroller and L293D Circuit Diagram

We can drive two DC Motors with one L293D, in this example we are using only the first pair of
drivers to drive one DC Motor. First pair of drivers are enabled by connecting EN1 to Logic
HIGH. IN1 and IN2 are connected to RB0 and RB1 of PIC Microcontroller respectively which
are used to provide control signal to the DC Motor. DC Motor is connected to OUT1 and OUT2
of the L293D.
MikroC Source Code

void main()

{ANSELB=0;

TRISB = 0; // PORT B as output port

PORTB = 1; // Set RB0 to high

While(1)

//To turn motor clockwise

PORTB.F0 = 1;

Delay_ms(2000);//2 seconds delay

//To Stop motor

PORTB = 0; // or PORTB = 3

Delay_ms(2000);//2 seconds delay

//To turn motor anticlockwise direction

PORTB.F1 = 1;

Delay_ms(2000);//2 seconds delay

//To Stop motor

PORTB = 0; // or PORTB = 3 (3 = 0b00000011)


Delay_ms(2000); // 2 seconds delay

LAB. Tasks:

1- Implement the previous code and connection

2- Write the code and draw the circuit needed to connect two push buttons
and one DC-motor to a PIC. If the first push button is pressed then the motor
will rotate clockwise for 3 second. If the second push button is pressed then
the motor will rotate counterclockwise for 3 second.

You might also like