Documente Academic
Documente Profesional
Documente Cultură
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.
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.
• 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.
• You can write to PORT and TRIS register entirely or bit by bit.
0 0b00000000 00 0x00
1 0b00000001 01 0x01
void main()
PORTB.F0 = 1; //LED ON
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.
• 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:
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;
While(1)
PORTB.F0 = 1; //LED ON
}}}
LAB. Tasks:
2- Modify the code and connection to perform 8bits up counter with 1-sec
delay between each count.
- 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.
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;
ansela=0;
anseld=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:
3- Using two push buttons and one seven-segment display write the needed
code to do the following:
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.
MikroC Pro provides built in libraries for interfacing LCDs with HD44780 compliant controllers
using 4 bit mode data transmission.
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
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
This function initializes the LCD module connected to the above defined pins of the PIC
Microcontroller.
2- Lcd_Out
This functions prints the text (string) in a particular row and column.
3- Lcd_Out_Cp
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
It prints the character (out_char) in the specified row and column of the LCD Screen.
5- Lcd_Chr_Cp
6- Lcd_Cmd
// Copy the first lines from: helpà indexà write LCDà at the end of page copy from the written program"
void main()
{ ANSELB=0;
}
LAB. Tasks:
- Each time the push button is pressed the LCD must count up by one.
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() {
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
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.
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;
While(1)
PORTB.F0 = 1;
PORTB = 0; // or PORTB = 3
PORTB.F1 = 1;
LAB. Tasks:
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.
LAB.7
Interfacing Relay with PIC Microcontroller
A relay is an electromagnetic switch which is used to switch High Voltage/Current using Low
power circuits. Relay isolates low power circuits from high power circuits. It is activated by
energizing a coil wounded on a soft iron core. A relay should not be directly connected to a
microcontroller, it needs a driving circuit.
A relay should not be connected directly to a microcontroller due to following reasons..
• A microcontroller is not able to supply current required for the working of a relay. The
maximum current that a PIC Microcontroller can source or sink is 25mA while a relay
needs about 50 – 100mA current.
• A relay is activated by energizing its coil. Microcontroller may stop working by the
negative voltages produced in the relay due to its back emf.
void main()
{ANSEB=0;
while(1)
If you want to use more relays, using transistors will be difficult. In these cases you may
use ULN2003or ULN2803. These are monolithic IC s consists of High Voltage High Current
Darlington transistor arrays. You can connect seven relays using ULN2003 and eight relays
using ULN2803. When using these driver ICs we don’t need to connect freewheeling diode as
they have built in clamp diodes.
MikroC Program
void main()
{ANSELD=0;
While(1)
}}
LAB. Tasks:
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. If the second push button is pressed then the motor will stop.
LAB. 8
Generating PWM with PIC Microcontroller using CCP Module
PWM is a technique used to generate analog output signal using digital signals. It is commonly
used to control average power delivered to a load, motor speed control, generating analog
voltage levels and for generating analog waveforms.
CCP Modules are available with a number of PIC Microcontrollers. CCP stands for
Capture/Compare/PWM. Using PWM module is far more easier and cost effective than using
extra chips for PWM generation. MikroC Pro for PIC Microcontroller provide built-in library
for PWM which makes our task very simple.
MikroC Functions
• PWM1_Init(constant long frequency) : This function initializes the PWM module with
duty ratio 0. Frequency parameter is the desired frequency in Hz. It should be a numeric
constant, should not be a variable.
• PWM1_Set_Duty(unsigned short duty_ratio) : This function is used to set the duty
cycle of the PWM. The parameter duty_ratio takes values from 0 to 255, ie 0 means 0% ,
127 means 50% and 255 means 100% duty cycle. The PWM1_Init() routine must be
called before using this.
• PWM1_Start() : This function starts the PWM output. PWM1_Init() must be called
before calling this routine,
• PWM1_Stop() : This function stops the PWM output. PWM1_Init() must be called
before calling this routine. PWM1_Start() should be called before calling this function
otherwise calling this function will not have any effect as PWM module is not running.
Note 1 : For microcontrollers with more than one CCP module, to use the desired CCP module
for PWM generation simply change the number “1” in the prototype with desired module
number. eg: PWM2_Init(5000), PWM2_Start().
Note 2 : All PWM modules in a PIC Microcontroller uses Timer 2 for its operation, so you
cannot set different frequencies for different PWM modules.
In robotics applications we may have to control the speed of the DC Motor. We will see how to
control the speed of a DC Motor using Pulse Width Modulation (PWM). By using PWM we can
easily control the average power delivered to a load and by thus we can easily control the speed
of the DC Motor.
DC Motor is interfaced with PIC Microcontroller using L293D Motor Driver. Two Push Button
switches are provided to control the speed of the motor. Here we are using 12V DC Motor and
average DC value delivered to motor can be varied by varying the duty ratio of the PWM. The
average DC Voltage of 0% duty cycle is 0V, 25% duty cycle is 3V, 50% duty cycle is 6V, 75%
duty cycle is 9V and for 100% duty cycle 12V.
void main()
ANSELD=0;
ANSELC=0;
ANSELB=0;
{ Delay_ms(40);
{Delay_ms(40);
PWM1_Set_Duty(duty); }
Delay_ms(10); // slow down change pace a little
The parameter of PWM1_Set_Duty() is duty ratio which ranges from 0 to 255, ie 0 means 0%
duty cycle and 255 means 100% duty cycle.
LAB. Tasks:
ADC module of PIC microcontroller have usually 5 input for 28 pin devices and 8 inputs for 40
pin devices. The conversion of analog signal to PIC ADC module results in corresponding 10 bit
digital number. PIC ADC module has software selectable high and low voltage reference input to
some combination of VDD, VSS, RA2 and RA3.
In the following example project we will convert analog input to channel 0 to 10 bit digital
number with low voltage reference (Vref-) 0v and high voltage reference (Vref+) 5V. The output
will be displayed using 10 LEDs. You can change the Vref- and Vref+ by configuring the
ADCON1 register.
0v = 0000000000
5v = 1111111111
= 5/1023
= 4.887 mV
Thus it means that for a change in 4.887mV, the binary output changes by 1.
Circuit Diagram
MikroC Program
void main()
{ANSELA=0b00000010;
ANSELC=0;
ANSELB=0;
ADC_Init();
While(1)
}.
You can vary the analog input value by varying the resistance of the potentiometer in the circuit.
A Digital Thermometer can be easily constructed using a PIC Microcontroller and LM35
Temperature Sensor. LM35 series is a low cost and precision Integrated Circuit Temperature
Sensor whose output voltage is proportional to Centigrade temperature scale. Thus LM35 has an
advantage over other temperature sensors calibrated in Kelvin as the users don’t require
subtraction of large constant voltage to obtain the required Centigrade temperature. It doesn’t
requires any external calibration. It is produced by National Semiconductor and can operate over
a -55 °C to 150 °C temperature range. Its output is linearly proportional to Centigrade
Temperature Scale and it output changes by 10 mV per °C.
The LM35 Temperature Sensor has Zero offset voltage, which means that the Output = 0V, at 0
°C. Thus for the maximum temperature value (150 °C), the maximum output voltage of the
sensor would be 150 * 10 mV = 1.5V. If we use the supply voltage (5V) as the Vref+ for Analog
to Digital Conversion (ADC) the resolution will be poor as the input voltage will goes only up to
1.5V and the power supply voltage variations may affects ADC output. So it is better to use a
stable low voltage above 1.5 as Vref+. We should supply Negative voltage instead of GND to
LM35 for measuring negative Temperatures.
This article only covers the basic working of Digital Thermometer using PIC Microcontroller
and LM35, and uses 5V as Vref+.
In the following MikroC Source Code the Analog output voltage of LM35 temperature sensor is
given to the Analog Input pin AN0 of the PIC Microcontroller. The result of the 10-bit Analog to
Digital (A/D) Conversion is read using the function ADC_Read(0). This 10-bit digital value is
then converted to the corresponding voltage by multiplying with 0.4887 (. Then the Voltage is
converted to temperature value by multiplying with 100 (1000/10).
MikroC Code
void main() {
ANSELE=0b00000010;
ANSELC=0;
TRISE=0b00000010;
ADC_Init();
while(1)
portc=temp_res;
Serial Transmission
In Serial Transmission only one bit of a byte is transmitted at a time. There is only one
communication line, thorough which bits are transmitted sequentially.
Data can be transmitted using Parallel or Serial techniques, as the pros and cons of two methods
are equal and the selection depends on application. Parallel Transmission is very fast compared
to serial transmission, as it transmits a byte at a time. Serial Transmission is cost effective as
compared to Parallel Transmission as it requires only one line for transmission.
Transmission Systems are also classified into 2 on the basis of transmission synchronization.
• Synchronous Transmission
• Asynchronous Transmission
USART is the most commonly used serial I/O module. It is also known as Serial
Communications Interface (SCI). USART can be easily configured as a full-duplex
asynchronous communication system that can communicate with peripheral devices, such
as personal computers and CRT terminals, or it can be configured as a half-duplex synchronous
communication system that can communicate with peripheral devices, such as serial EEPROMs,
A/D or D/A integrated circuits, etc. USART can be configured in the following modes.
We don’t want to bother about configuring USART registers as MikroC Pro for PIC
Microcontrollers have built-in library function to handle asynchronous communication.
Circuit Diagram
The above circuit can demonstrate the PIC to PIC Communication using USART. Here we are
using Asynchronous communication. The switch status read by the first PIC is transmitted to the
second PIC and displayed using LED’s.
MikroC Code
Transmitter
void main()
{ ANSELB=0;
TRISB = 0xFF;
PORTB = 0;
while (1)
{ // Endless loop
Delay_ms(500);
Receiver
void main()
{ ANSELB=0;
TRISB = 0;
PORTB = 0;
while (1)
{ // Endless loop
if (UART1_Data_Ready())
{ // If data is received,
}}
UART Library
The UART hardware module is available with a number of PIC compliant MCUs. The mikroC
PRO for PIC UART Library provides comfortable work with the Asynchronous (full duplex)
mode.
You can easily communicate with other devices via RS-232 protocol (for example with PC, see
the figure at the end of the topic – RS-232 HW connection).
Important :
• UART library routines require you to specify the module you want to use. To select the
desired UART module, simply change the letter x in the routine prototype for a number
from 1 to 2. (UART1 pins RC6à TX, RC7àRX. UART2 pins RB5àTX, RB2àRX)
• To connect PIC with computer we need level converter IC from TTL to RS232 and vice-
versa “e.g. MAX232 IC ”
• You can use Mikroc USART Terminal tool to send and receive from computer.
LAB. Tasks:
2- Build full connection and write a program that send to computer 10 bytes
using PIC serial pins at baud rate =19200 bits/sec. Note: (RC6:TX, RC7:RX)
LAB. 11
Using Interrupts
PIC Microcontroller consists of both Hardware and Software Interrupts. If the interrupts are
generated by external hardware at certain pins of microcontroller, or by inbuilt devices like
timer, they are called Hardware Interrupts. While Software Interrupts are generated by a piece of
code in the program. Also known as External and Internal Interrupts.
INTCON Register
INTCON Register is a readable and writeable register which contains various enable and flag
bits for External and Internal Interrupts.
1 – At least one of the RB7 – RB4 pins changed state, a mismatch condition will continue to set
the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared. It must
be cleared in software.
0 – None of the RB7 – RB4 pins have changed state
INTEDG bit of OPTION_REG Register is the Interrupt Edge Select bit. When it is 1 interrupt
is on rising edge of RB0/INT pin and when it is 0 interrupt is on falling edge of RB0/INT pin.
Circuit Diagram
A push button switch is connected to the External Interrupt pin INT of the PIC Microcontroller.
When this button is pressed, the microcontroller is interrupted and the ISR is executed. The
ISR toggles the status of PORTC for 1 second.
MikroC Code
Interrupts can be easily handled by using reserved word ‘interrupt’. MikroC PRO for PIC
Microcontrollers implicitly declares a function ‘interrupt’ to handle interrupts which cannot be
redeclared.
void main()
{ ANSELB=0;
ANSELC=0;
TRISB=1;
while(1)
PORTC = 0x00;
}
LAB. Tasks:
Stepper Motor
A Stepper Motor is a brushless, synchronous DC electric motor, which divides the full rotation
into a number of equal steps. It finds great application in field of microcontrollers such as
robotics. Unipolar Motor is the most popular stepper motor among electronics hobbyist because
of its ease of operation and availability.
Stepper Motor can be easily interfaced with PIC Microcontroller by using readymade ICs such as
L293D or ULN2003. There are three different types of stepping modes for unipolar stepper
motor: wave, full, half drive. In this Lab. we will use full drive
In this mode two stator electromagnets are energised at a time. It is the usual method used for
driving and the motor will run at its full torque in this mode of driving.
1 0 0 1 1
2 0 1 1 0
3 1 1 0 0
4 1 0 0 1
void main()
ANSELB=0;
PORTB = 0x0F;
While(1)
PORTB = 0b00000011;
Delay_ms(500);
PORTB = 0b00000110;
Delay_ms(500);
PORTB = 0b00001100;
Delay_ms(500);
PORTB = 0b00001001;
Delay_ms(500);
}
LAB. Tasks:
2- Write the needed code to control stepper motor speed using push button
LAB. 13
Projects LAB
2- DC-motor
3- Graphical LCD
4- Temperature sensor
5- Serial communication
6- Stepper motor
7- Relay module