Sunteți pe pagina 1din 62

Embedded System Lab.

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 Segment Displays:

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:

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.
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.

Interfacing Relay with PIC Microcontroller using Transistor


A relay can be easily interfaced with microcontroller using a transistor as shown
below. Transistor is wired as a switch which carries the current required for operation of the
relay. When the pin RB7 of the PIC microcontroller goes high, the transistor BC547 turns On
and current flows through the relay. The diode D1 is used to protect transistor and the
microcontroller from Back EMF generated in the relays coil. Normally 1N4148 is preferred as it
is a fast switching diode having a peak forward current of 450mA. This diode is also known as
freewheeling diode.
MikroC Program

void main()

{ANSEB=0;

TRISB.F7 = 0; //Makes RB7 a output pin

while(1)

PORTB.F7 = 1; //Turns ON relay

Delay_ms(1000); // 1000 mS delay

PORTB.F7 = 0; //Turns OFF realy

Delay_ms(1000); //1000mS delay

Interfacing Relay with PIC Microcontroller using ULN2003

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;

TRISD = 0x00; //Make PORTD as output

While(1)

PORTD.F1 = 1; //Turns ON relay 1

PORTD.F2 = 1; //Turns ON relay 2

PORTD.F3 = 1; //Turns ON relay 3

PORTD.F4 = 1; //Turns ON relay 4

PORTD.F5 = 1; //Turns ON relay 5 ...etc..

Delay_ms(1000); // 1 second Delay

PORTD.F1 = 0; //Turns OFF relay 1

PORTD.F2 = 0; //Turns OFF relay 2

PORTD.F3 = 0; //Turns OFF relay 3

PORTD.F4 = 0; //Turns OFF relay 4

PORTD.F5 = 0; //Turns OFF relay 5 ...etc...

Delay_ms(1000); //1 second Delay

}}
LAB. Tasks:

1- Implement the previous codes and connections

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.

Note 3 : PWM1 pin is RC2. PWM2 pin is RC1.

DC Motor Speed Control using PWM with PIC Microcontroller

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.

Circuit Diagram – DC Motor Speed Control

DC Motor Speed Control using PWM with PIC Microcontroller


MikroC Code

void main()

{short duty = 0; //initial value for duty

ANSELD=0;

ANSELC=0;

ANSELB=0;

TRISD = 0xFF; //PORTD as input

TRISC = 0x00; //PORTC as output

TRISB = 0x00; //PORTB as output

PORTB = 0x02; //Run motor in anticlock wise

PWM1_Init(1000); //Initialize PWM1

PWM1_Start(); //start PWM1

PWM1_Set_Duty(duty); //Set current duty for PWM1

while (1) // endless loop

{if (!portd.f0 && duty<250) //if button on RD0 pressed

{ Delay_ms(40);

duty = duty + 10; //increment current_duty

PWM1_Set_Duty(duty); //Change the duty cycle }

if (!portd.f1 && duty >0) //button on RD1 pressed

{Delay_ms(40);

duty = duty - 10; //decrement duty

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:

1- Implement the previous code and connection

2- Control LED lighting using PWM.


LAB.9
Analog to Digital Converter (ADC) in PIC Microcontroller

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

Resolution = (Vref+ – Vref-)/(1024-1) (as it is 10 bit ADC)

= 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

unsigned int adc;

void main()

{ANSELA=0b00000010;

ANSELC=0;

ANSELB=0;

TRISA = 0x02; // PORTA is input


TRISC = 0; // Pins RC7, RC6 are outputs

TRISB = 0; // PORTB is output

ADC_Init();

While(1)

adc = ADC_Read(1); // Get 10-bit results of AD conversion of channel 1

PORTB = adc; // Send lower 8 bits to PORTB

PORTC = adc >> 8; // Send 2 most significant bits to RC1, RC0

}.

You can vary the analog input value by varying the resistance of the potentiometer in the circuit.

Digital Thermometer using PIC Microcontroller and LM35 Temperature Sensor

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

unsigned int temp_res;

void main() {

ANSELE=0b00000010;

ANSELC=0;

TRISE=0b00000010;

TRISC = 0; // PORTC is output

ADC_Init();

while(1)

temp_res = ADC_Read(6); // Get 10-bit results of AD conversion

temp_res = (((temp_res * 5.0)/1024)/10)*1000;

portc=temp_res;

• User guide pages 29 and 30 shows hardware connections details.


LAB. Tasks:

1- Implement the previous code and connection

2- Write the needed code to switch-ON a LED if room temperature is more


than 30C.
LAB.10
PIC to PIC Communication using UART

Serial Transmission

Serial Data 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 – Universal Synchronous Asynchronous Receiver Transmitter

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.

• Synchronous Master – Half Duplex


• Synchronous Slave – Half Duplex
• Asynchronous – Full Duplex

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

PIC to PIC Communication using USART

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;

UART1_Init(9600); // Initialize UART module at 9600bps

Delay_ms(100); // Wait for UART module to stabilize

while (1)

{ // Endless loop

UART1_Write(PORTB); // and send data via UART

Delay_ms(500);

Receiver

void main()

{ ANSELB=0;

TRISB = 0;

PORTB = 0;

UART1_Init(9600); // Initialize UART module at 9600bps

Delay_ms(100); // Wait for UART module to stabilize

while (1)

{ // Endless loop
if (UART1_Data_Ready())

{ // If data is received,

PORTB = UART1_Read(); // read the received data,}

}}

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:

1- Implement the previous codes and connections

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 is used to configure External Interrupts.

INTCON Register

INTCON Register is a readable and writeable register which contains various enable and flag
bits for External and Internal Interrupts.

GIE – Global Interrupt Enable

1 – Enables all unmasked interrupts


0 – Disables all interrupts

PEIE – Peripheral Interrupt Enable

1 – Enables all unmasked peripheral interrupts


0 – Disables all peripheral interrupts
TMR0IE – Timer 0 Overflow Interrupt Enable
1 – Enables the TMR0 interrupt
0 – Disables the TMR0 interrupt

INTE – RB0/INT External Interrupt Enable

1 – Enables the RB0/INT external interrupt


0 – Disables the RB0/INT external interrupt

RBIE – RB Port Change Interrupt Enable

1 – Enables the RB port change interrupt


0 – Disables the RB port change interrupt

TMR0IF – Timer 0 Overflow Interrupt Flag

1 – TMR0 register has overflowed. It must be cleared in software.


0 – TMR0 register did not overflow

INTF – RB0/INT External Interrupt Flag

1 – The RB0/INT external interrupt occurred. It must be cleared in software.


0 – The RB0/INT external interrupt did not occur
RBIF – RB Port Change Interrupt Flag

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 interrupt() // ISR

INTCON.INTF=0; // Clear the interrupt 0 flag

PORTC=~PORTC; // Invert (Toggle) the value at PortD

Delay_ms(1000); // Delay for 1 sec

void main()

{ ANSELB=0;

ANSELC=0;

TRISB=1;

TRISC = 0; // To configure PORTC as output port

OPTION_REG.INTEDG = 1; // Set Rising Edge Trigger for INT

INTCON.GIE = 1; // Enable The Global Interrupt

INTCON.INTE = 1; // Enable INT

while(1)

PORTC = 0x00;

}
LAB. Tasks:

1- Implement the previous code and connection

2- Re-implement Task-3 from LAB 1+2 using interrupt


LAB. 12

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

According to stepper motor wires color:

Black (D) orange (C) yellow (B) brown (A)


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.

Full Drive Stepping Sequence

Step D (D3) C (D2) B (D1) A (D0)

1 0 0 1 1

2 0 1 1 0

3 1 1 0 0

4 1 0 0 1

Interfacing using ULN2003


MikroC Code for Full Drive

void main()

ANSELB=0;

TRISB = 0; // PORT B as output port

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:

1- Implement the previous code and connection

2- Write the needed code to control stepper motor speed using push button
LAB. 13

Projects LAB

Use at least two of the following to design useful project.

1- Motion sensor module "ENABEL: PORTE.F1, INPUT SIGNAL: PORB.F0"

2- DC-motor

3- Graphical LCD

4- Temperature sensor

5- Serial communication

6- Stepper motor

7- Relay module

S-ar putea să vă placă și