Professional Documents
Culture Documents
EE313
Sem-1, 2015
COURSE DESCRIPTION
Provides knowledge
microprocessors and
operation of digital
techniques to use
applications
Involves elements of
programming for P
assembly
and
language
Recommended textbooks:
Embedded C Programming and the Microchip PIC by Richard Barnett, L
OCull and S Cox, Thomson Delmarr learning
Programming and Customizing PIC micro MCU microcontrollers. McGraw
Hill, U.S.A. (Second Edition)
Interfacing PIC Microcontrollers, Embedded Design by Interactive Simulation 2nd edition - By Martin Bates
PICmicroTM Mid-Range MCU Family Reference Manual, Microchip
Programming and Customizing the PIC Microcontroller, Myke Predko - Third
Edition
Week
7
14
Weekly
%
10%
10%
10%
14
20%
End of Semester
50%
Time table
Timetable
Session
Lecture
Lab
Tutorial
Day
Tue
Wed
Thu
Wed
Thu
Mon
Wed
Mon
Fri
Time
1-2pm
4-5pm
10-11am
1-4pm
3-6pm
2-5pm
11-am
6-7pm
1-2pm
093-207
003-001
014-112
Room
014-112 014-112
014-028
Introduction
Base-10 number system i.e. Decimal number
system
Because we use ten different digits (0, 1, 2, ... 8, 9)
Continue
Very important to learn how to convert numbers from one number system to
another, i.e. how to turn a sequence of zeros and ones into understandable
values
BINARY TO DECIMAL NUMBER CONVERSION: Eg. (1 1 0)2 = ( )10
Bit (0 or 1)
Byte ( group of 8 bits )
Nibble ( group of 4 bits)
Word ( group of 16 bits)
MSB: The greatest value has the leftmost bit called the most
significant bit (MSB)
LSB: The rightmost bit has the least value and is therefore
called the least significant bit (LSB)
Organization:
Arithmetic Logic Unit (ALU)
Control unit,
Registers
Accumulator:
It is 8 bit general purpose register (eg. 8085 processor).
It is connected to ALU.
Most of the operations are done in Acc.
Temporary register:
It is not available for user
All the arithmetic and logical operations are done in the temporary register
but user cant access it.
Flag:
Use to know status of various operations done.
Flag Register along with Accumulator is called PSW or Program Status
Word.
Memory Interfacing
Example: Interface 2Kbytes of Memory to P (8-bit) with
starting address 8000H
Initially we realize that 2K memory requires 11 address lines
(2^11=2048). So we use A0-A10 .
Write down A15 A0
A15
14
13
12
11
10 A9 A8 A7 A6 A5 A4 A3 A2 A1
1
---
0
---
0
---
0
---
0 0 0 0
--- --- ---
0 0 0
--- --- ---
0
---
A0
Memory Interfacing
The diagram of 2KB interfacing is shown below:
A15- A11
3:8
DECODER
P IC
CS
A15-A8
ALE
A10- A0
AD7-AD0
WR RD
IO/M
Latch
A7- A0
2K Byte
Memory
Chip
D7- D0
RD
WR
High-Level Language:
Because it is not fun to program in Assembly, we have high level
programming languages like C, CPP, Forton etc..
Compilers are used to translate high-level language program to
machine language.
Advantages:
Fast program development.
Testing and debugging a program is easier than in the assembly
language.
Portability of a program from one machine to other.
Program Translation
Flash Memory
Similar to UV EPROM.
Content of this memory can be written and cleared practically an unlimited
number of times
Flash ROM are ideal for learning, experimentation and small-scale production
Introduction
Why we use C?
C is a portable language intended to have minimal modification
when transferring programs from one computer to another.
Main program flow will basically remain unchanged, while the
various setup and port/peripheral control will be micro specific.
An example of this is the port direction registers on a
PICmicroMCU are set 1=Input 0=Output, whereas the H8 is
0=Input and 1=Output
Use of C in C applications: as manufacturers providing larger
program and RAM memory areas in addition to faster operating
speeds
An example quoted to me as a non believer was: to create a stop
clock function would take 2/3 days in C or 2 weeks in assembler.
C fundamentals
Structure of C Programs
All C program contain preprocessor directives, declarations, definitions, expressions,
statements and functions
Preprocessor directive
Two most common preprocessor directives:
#define directive, which substitutes text for the specified identifier, and
#include directive, which includes the text of an external file into a program
Declaration
Variables, functions, and types used in the program
Global variables are declared outside functions
A local variable is declared inside a function
Definition
A definition establishes the contents of a variable or function
Allocates the storage needed for variables and functions
Function
A function is a collection of declarations, definitions, expressions, and statements that
performs a specific task
#include <stdio.h>
/* My first C program */
main()
{
printf(Hello world!);
}
Statement #include <stdio.h> tells the compiler to include the source code from the file
stdio.h into the program.
STandarD Input and Output header file, contains most of the input and output
functions
FunctionName()
{
code
}
if (ThisIsTrue)
DoThisFunction();
PIC18F6722 board
PIC18F8722 board
PIC FAMILIES
PIC stands for Peripheral Interface Controller given by Microchip Technology
Single-chip microcontrollers
http://www.microchip.com/stellent/images/mchpsiteimages/en537986.jpg
Baseline
Architecture
Mid-Range
Architecture
Enhanced Mid-Range
Architecture
PIC18 Architecture
Pin Count
6-40
8-64
8-64
Interrupts
No
Single interrupt
capability
Single interrupt
Multiple interrupt capability
capability with
with hardware context save
hardware context save
Performance
5 MIPS
5 MIPS
8 MIPS
Up to 16 MIPS
Instructions
33, 12-bit
35, 14-bit
49, 14-bit
83, 16-bit
Program
Memory
Up to 3 KB
Up to 14 KB
Up to 28 KB
Up to 128 KB
Data Memory
Up to 138 Bytes
Up to 4 KB
Features
Comparator
8-bit ADC
Data Memory
Internal Oscillator
In addition to
Baseline:
SPI/IC
UART
PWMs
LCD
10-bit ADC
Op Amp
In addition to
Mid-Range:
Multiple
Communication
Peripherals
Linear Programming
Space
PWMs with
Independent Time
Base
In addition to
Enhanced Mid-Range:
8x8 Hardware Multiplier
CAN
CTMU
USB
Ethernet
12-bit ADC
Families
PIC12, PIC16
PIC12FXXX, PIC16F1XX
PIC18
8-bit architecture
18-100
Description
PIC Peripheral Interface Controller
Made by Microchip Technology
Most popular by industry developers and hobbyists
o Low cost (cents to dollars)
o Availability
o Extensive application notes
o USB programming
RAM
PC, special purpose
registers
http://www.microchip.com/_images/BaselineArch_large.jpg
One accumulator
Bank switching
NO multi-tasking
HARVARD ARCHITECTURE
2 MB
221
8 bit
4 KB
212
Microprocessor Unit (1 of 3)
Includes Arithmetic Logic
Unit (ALU), Registers,
and Control Unit
Arithmetic Logic Unit
(ALU)
WREG working register
Status register that stores
flags
Instruction decoder when
the instruction is fetched it
goes into the ID
Microprocessor Unit (2 of 3)
Registers
Microprocessor Unit (3 of 3)
Control unit
Provides timing and control signals to various Read and Write operations
Control signals
Read and Write
PIC18F8722 MCU
Data Memory: 4 K
Address range: 000 to FFFH
Data EEPROM
1K
Not part of the data memory space
Addressed through special function registers
PIC18F8722
Internal
Block diagram
Features of PIC
Brown-out-reset means when the power supply goes below a specified
voltage (say 2V), it causes PIC to reset; hence malfunction is avoided.
Watch dog timer (user programmable) resets the processor if the
software/program ever malfunctions and deviates from its normal
operation.
Sleep Mode: Power consumption of the microcontroller is reduced to
the lowest level in Sleep mode since the main power consumer - the
oscillator - doesnt operate. Set the microcontroller in this mode- by
executing the SLEEP instruction
Z - Zero bit
1 - The result of an arithmetic or logic operation is zero.
0 - The result of an arithmetic or logic operation is different from zero.
DC - Digit carry/borrow bit is changed during addition and subtraction if an
overflow or a borrow of the result occurs.
1 - A carry-out from the 4th low-order bit of the result has occurred (same as
auxiliary carry)
0 - No carry-out from the 4th low-order bit of the result has occurred
C - Carry/Borrow bit is changed during addition and subtraction if an overflow or a
borrow of the result occurs, i.e. if the result is greater than 255 or less than 0.
1 - A carry-out from the most significant bit (MSB) of the result has occurred.
0 - No carry-out from the most significant bit (MSB) of the result has occurred.
3. OPTION_REG Register
3. OPTION_REG Register
PSA - Prescaler Assignment bit assigns prescaler (only one exists) to the timer or
watchdog timer.
1 - Prescaler is assigned to watchdog
0 - Prescaler is assigned to a free-run timer TMR0
PS2, PS1, PS0 Prescaler Rate Select bits..will be explained in Timer section
PIC C -functions:
SET_TRIS_x()
configured as outputs
...
Port B
Built in pull-up resistors, which make them ideal for connection to push buttons
(keyboard), switches and opto-couplers
In order to connect these resistors to the microcontroller ports, the appropriate
bit of the WPUB register should be set
PIC C function:
PORT_B_PULLUPS()
To enable pins to cause an interrupt, appropriate bit of the
IOCB register should be set
Aim: /* The PORTB.1 pin is configured as a digital input. Any change of its logic state will cause
an interrupt. It also has a pull-up resistor. All other PORTB pins are digital outputs.*/
ANSEL = ANSELH = 0;
// All I/O pins are configured as digital
PORTB = 0;
// All PORTB pins are cleared
TRISB = 0b00000010;
// All PORTB pins except PORTB.1 are configured as outputs
RBPU = 0;
// Pull-up resistors are enabled
WPUB1 = 1;
// Pull-up resistor is connected to the PORTB.1 pin
IOCB1 = 1;
// The PORTB.1 pin may cause an interrupt on logic state change
RBIE = GIE = 1;
// Interrupt is enabled
...
INTCON Register contains various enable and flag bits for TMR0 register overflow,
PORTB change and external INT pin interrupts.
Continue..
T0IE - TMR0 Overflow Interrupt Enable bit timer interrupt
1 - Enables the TMR0 interrupt.
0 - Disables the TMR0 interrupt.
INTE - RB0/INT External Interrupt Enable bit external interrupt
1 - Enables the INT external interrupt.
0 - Disables the INT external interrupt.
RBIE - RB Port Change Interrupt Enable bit. - when use PORTB pins as interrupt
1 - Enables the port B change interrupt
0 - Disables the port B change interrupt
T0IF - TMR0 Overflow Interrupt Flag bit registers the timer TMR0 register overflow, when
counting starts at zero.
1 - TMR0 register has overflowed (bit must be cleared from within the software)
0 - TMR0 register has not overflowed
INTF - RB0/INT External Interrupt Flag bit registers the change of the RB0/INT pin logic
state.
1 - The INT external interrupt has occurred (must be cleared from within the software).
0 - The INT external interrupt has not occurred.
RBIF - RB Port Change Interrupt Flag bit registers any change of logic state of some PORTB
input pins.
1 - At least one of the PORTB general purpose I/O pins has changed state. Upon reading
PORTB, the RBIF bit must be cleared from within the software.
0 - None of the PORTB general purpose I/O pins has changed the state.
Timers in PIC
PIC18F8722: 5 timer modules - denoted by the symbols TIMER-0(8b or 16b),
TIMER-1(16b), TIMER-2(8b), TIMER-3(16b), TIMER-4(8b)
Modules help to perform various timing and counting functions inside the chip
For examples,
8 bit timers - These can count between between 0-255
16 bit timers - These can count between 0-65536
32 bit timers - These can count between 0-4294967296
PIC ranges from 1 MHz to 40Mhz, this can be sometimes too fast!
Prescaler: Help to divide the CPU clock to obtain a smaller frequency: Gives
large time delay
TIMER 0: TMR0
Timer 0 Operation
Overflow
An overflow occurs when a timer register has already counted the maximum value it can
count. At overflow the counter value become 0 again. For example when an 8 bit timer
has the value 255 and receive another clock that will set it to 0 and generate an
overflow. An overflow can trigger an interrupt and the ISR can handle it.
TIMER0 is configured as follows.
8 Bit Mode
Clock Source from Prescaler
Prescaler = FCPU/256 (Note: FCPU= Fosc/4)
Over flow INT enabled
1.
2.
3.
4.
Example: Generate 1 sec delay and on LED for 1 sec using Timer_0. Take 20 MHz clock
frequency
When an over flow occurs the program jumps to ISR, where we increment the counter. And
when counter becomes 76 we toggle RB4 pin. This pin is connected to LED. Therefore we
have a LED which is ON for 1 sec and Off for 1sec.
unsigned char counter=0;//Overflow counter
void main()
{
//Setup Timer0
T0PS0=1; //Prescaler is divide by 256
T0PS1=1;
T0PS2=1;
//Clear Flag
TMR0IF=0;
} }
}
main() {
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256|RTCC_8_BIT);//Timer 0 setup
enable_interrupts(INT_RTCC);//enable timer0 and global interrupts
enable_interrupts(GLOBAL);
output_low(PIN_A5); // LED ON
while(1); // Wait for the interrupt
Solution:
#use delay (clock=20000000)
#INT_TIMER0 //Timer 0 interrupt routine 16 bit mode example
timer0_16bit()
{
i++;
if(i==3) // check for about 10 sec
{if(lowt==1)lowt=0;
else lowt=1;
i=0;
if(lowt==0)output_high(PIN_B5); // LED OFF
else output_low(PIN_B5); // LED ON
}
}
void main() {
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256);//Timer 0 setup 16 bit mode
enable_interrupts(INT_RTCC);//enable timer0 and global interrupts
enable_interrupts(GLOBAL);
output_low(PIN_B5); // LED ON
while(1); // Wait for the interrupt
}// end of program
#include <18F8722.h> //
int i=0;
Program for Timer 1 , Generate 10 sec delay trigger
#INT_TIMER1
void timer1interrupt() // program automatically jump on ISR when overflow occurred
{
i++; // count for 19 to make 10 sec
if (i==19)
{if (input(PIN_D0)==true)
output_low(PIN_D0);
else
output_high(PIN_D0);
i=0; // reset the count
}
}
main() {
setup_timer_1(T1_INTERNAL | T1_DIV_BY_8);
//Prescaler clock divide by 8
enable_interrupts(INT_TIMER1); // Enable Timer 1 interrupt
enable_interrupts(GLOBAL); // Enable Global interrupt
output_low(PIN_D0); // Set first pin D_0 low
while(1); // Wait for the interrupt
}// end of program
Timer 1 Module
Features:
Software selectable operation as a 16-bit timer or counter
Readable and writable 8-bit registers (TMR1H and TMR1L)
Selectable clock source (internal or external) with device clock or Timer1 oscillator
internal options
Module incorporates its own low-power oscillator to provide an additional clocking
option
Also used to provide Real-Time Clock (RTC) functionality to applications with only a
minimal addition of external components and code overhead
LOW-POWER TIMER1 OPTION
Timer1 oscillator can operate at two distinct levels of power consumption based on
device configuration
When the LPT1OSC Configuration bit is set, the Timer1 oscillator operates in a lowpower mode. When LPT1OSC is not set, Timer1 operates at a higher power level.
Higher power level: Power consumption for a particular mode is relatively constant,
regardless of the devices operating mode. The default Timer1 configuration is the
higher power mode.
Low-power: Timer1 mode tends to be more sensitive to interference, high noise
environments may cause some oscillator instability. The low-power option is, therefore,
best suited for low noise applications where power conservation is an important design
consideration
Aim: Each overflow in the Timer1 register consisting of TMR1H and TMR1L,
causes an interrupt to occur. In every interrupt routine, variable cnt will be
incremented by 1.
unsigned short cnt;
void interrupt() {
cnt++ ;
// Interrupt causes cnt to be incremented by 1
PIR1.TMR1IF = 0;
// Reset bit TMR1IF
TMR1H = 0x80;
// TMR1H and TMR1L timer registers are returned
TMR1L = 0x00;
// their initial values
}
void main() {
ANSEL = ANSELH = 0; // All I/O pins are configured as digital
T1CON = 1;
// Turn on timer TMR1
PIR1.TMR1IF = 0; // Reset the TMR1IF bit
TMR1H = 0x80; // Set initial value for timer TMR1 (1280)
TMR1L = 0x00;
PIE1.TMR1IE = 1; // Enable an interrupt on overflow
cnt = 0; // Reset variable cnt
INTCON = 0xC0; // Enable interrupt (bits GIE and PEIE)
...
#include <18F8722.h>
#device ICD=TRUE
#fuses HS,NOLVP,NOWDT
#use delay (clock=20000000)
+5v
Y
A
B
Y
+5 v
Two cross-coupled NAND gates form a very simple SetReset (SR) latch
Design requires a double-throw switch
Two pull-up resistors generate a logic one for the gates;
the switch pulls one of the inputs to ground
to low transition
int keyread(void){
if(input(PIN_A0)==0)
{while (input(PIN_A0)==0);
return(1); }
}
Call this function in main function
Method 2: Low
to High transition
int keyread(void){
if(input(PIN_A0))
{while (input(PIN_A0));
return(1); }
}
void main(void)
{ Call this function in main function
int keyno=0;
Port
D
Port
A
output_high(PIN_A0);
output_low(PIN_A1);
output_low(PIN_A2);
output_low(PIN_A3); // select ones segment
output_D(h_code[Segments[0]]); // output 7-seg code from array
delay_ms(5);
output_low(PIN_A0);
output_high(PIN_A1);
output_low(PIN_A2);
output_low(PIN_A3);
output_low(PIN_A0);
output_low(PIN_A1);
output_low(PIN_A2);
output_high(PIN_A3);
Home exercise:
Now our goal is to construct a simple 0-9999 seconds
count down timer with an alarm and a display.
The time is set through two input switches (named INC
and TSET for setting time and turning the timer on)
and the count down seconds are displayed on a 4-digit
seven segment LED display.
Time out condition is to indicate by an audible alarm
from a buzzer
External Interrupt
How we can capture a pulse to generate/ activate an
interrupt in PIC?
interrupts:
RB0/INT0,
RB1/INT1,
Take an Example
Design a digital dice using PIC microcontroller such
that
Continuous display number is not readable to user on
Screen
When user presses a button, exactly same time, display
number is stopped and visible to the user
Make this application real-time
Suggest circuit connection
Push - button
PORTB Interrupt-on-Change
An input change on PORTB<7:4> sets flag bit,
RBIF (INTCON<0>)
Interrupt
can
be
enabled/disabled
by
setting/clearing enable bit, RBIE (INTCON<3>).
Interrupt priority for PORTB interrupt-on-change
is determined by the value contained in the
interrupt priority bit, RBIP (INTCON2<0>).
Gnd
Analog-To-Digital Converter
Total 16 separate analog inputs/channels (AD0-AD15) in
18F8722 and 12 in 18F6722
A 10-bit binary ADC
A/D converter converts an analog input signal into a 10-bit binary
number
Method: Successive Approximation Convertor
Store the conversion results into the ADC registers (ADRESL and
ADRESH);
Minimum resolution or quality of conversion may be adjusted to
various needs by selecting voltage references RA2/AN2/Vref- and
RA3/AN3/Vref+.
A/D converter has a unique feature of being able to operate while the
device is in Sleep mode. To operate in Sleep, the A/D conversion
clock must be derived from the A/Ds internal RC oscillator.
Temperature sensor
LM35
Resolution
= (Vref+ Vref-)/(1024-1) (as it is 10 bit ADC)
= 5/1023
= 4.887 mV
An input of 4.887mV would give us a reading of 00--01
An input of 9.776mV would give us a reading of 00--0, and so on.
Without
ADC
Interrupt
/* ADC Initialization */
setup_adc(ADC_CLOCK_INTERNAL);
// initialize ADC with a sampling rate of Crystal/4 MHz
setup_adc_ports( ALL_ANALOG );
set_adc_channel(1);
// point ADC to channel 1 (RA1/AN1) for reading
delay_ms(1);
// ADC module is slow, needs some time to adjust.
continue..next slide
Continue..
Sensors
1. Humidity and Temperature Sensor - RHT03/DHT-22
Low cost humidity and temperature sensor with a single wire digital
interface
Already calibrated and doesnt require extra components so you can get
right to measuring relative humidity and temperature
Features:
3.3-6V Input
1-1.5mA measuring current
40-50 uA standby current
Humidity from 0-100% RH
-40 to 80 degrees C temperature range
+-2% RH accuracy
+-0.5 degrees C
Operation:
Measures distance using sonar; an ultrasonic (well above
human hearing range) pulse is transmitted from the unit
and distance-to-target is determined by measuring the
time required for the echo return.
Output from the sensor is a variable-width pulse that
corresponds to the distance to the target
Applications and Uses
UAV blimps, micro planes and some helicopters
Bin level measurement
Proximity zone detection
People detection
Robot ranging sensor
Autonomous navigation
Multi-sensor arrays
Distance measuring
Long range object detection
Wide beam sensitivity
Principle of operation
TS601 module with a impulse
through SIG, the trailing edge
springs, and transmits a string of
ultrasonic signal of 40KHz when
the module receives it. Then the
electrical level of SIG stitch will
be risen. The duration of high level
T3 will be ensured by the distance
between the object and the
telemeter. After 19.5ms, the high
level descends, when no object is
in a distance of 3M. The host
computes the distance though the
impulse width input by the
electronic
eye
module:
S=(V*T3)/2.
Applications
Touch-less switch (Sanitary equipment, Control of illumination, etc. )
Sensor for energy saving (ATM, Copier, Vending machine, Laptop computer, LCD
monitor)
Amusement equipment (Robot, Arcade game machine)
Example:
In the following circuit, the analog input is connected to pin#3 (RA1/AN1). You can vary
the analog input value by varying the resistance of the potentiometer (10K) in the circuit.
The output will be displayed using 10 LEDs, connected common cathodes to Port B and
Port C0-1. Use low voltage reference (Vref-) 0v and high voltage reference (Vref+) 5V.
i. Write a PIC C program to setup for converting input analog signal into equivalent 10-bit
output. Turn on/off LEDs as per the digital output.
ii. Draw the flowchart of operation, to convert continuous analog input into digital output.
iii. Find the resolution of the conversion for the 10 bit digital output.
2. Stepper Motor
Work in a similar way to DC motors, but where DC motors have one
electromagnetic coil to produce movement, stepper motors contain many
Stepper motors are controlled by turning each coil on and off in a
sequence
Every time a new coil is energized, the motor rotates a few degrees,
called the step angle.
For example, a stepper motor with a step angle of 7.5 degrees requires
48 pulses for a complete revolution! (3600)
applications:
robotics
and
1. Wave Drive
In this mode only one electromagnet is energized at a
time
Generated torque will be less when compared to full
drive But Power consumption is reduced
It has same number of steps as in the full drive
This drive is preferred when power consumption is
more important than torque (It is rarely used!)
Wave Drive Stepping Sequence
Step
2. Full Drive
In this mode two electromagnets are energized at a
time, so the torque generated will be larger when
compared to Wave Drive
Commonly used, Power consumption will be higher
than other modes
Full Drive Stepping Sequence
Step
3. Half Drive
In this mode alternatively one and two electromagnets are
energized, so it is a combination of Wave and Full drives
This mode is commonly used to increase the angular resolution
of the motor but the torque will be less, about 70% at its full
step position
We can see that the angular resolution doubles when using Half
Drive.
Half Drive Stepping Sequence
Step
Stepper
Motor
SN754410
void main(void)
{
char st_code[4]= {0x0C,0x06,0x3,0x09}; // clock wise rotation-full wave drive
%char st_code1[4]= {0x08,0x04,0x02,0x01}; // clock wise rotation- wave drive
%char st_code2[4]= {0x01,0x02,0x04,0x08}; // anti-clock wise rotation - wave
int i=0;
while(1)
{
for(i=0; i<4; i++){
output_B(st_code[i]); // output to port B to drive Stepper
delay_ms(10); //delay between two steps
}
}
}
3. Servo Motor
Special geared DC motor equipped with an electronic circuit for
controlling the direction of rotation, as well as the position, of the
motor shaft
Because servo motors allows precise angular positioning of their
output shaft
Very useful in robotics and radio-controlled cars, airplanes, and
boats to control the motion of their various parts.
DC Motor
L293
Period=51.2 S
#include <18F6722.h>
#device ICD=TRUE
#fuses HS,NOLVP,NOWDT
#use delay (clock=40000000)
main() {
// PWM Configurations
setup_timer_2(T2_DIV_BY_1,255,1); // Set PWM frequency
setup_ccp1(CCP_PWM); // Configure CCP1 to PWM mode
set_pwm1_duty(512); // 50% duty cycle (Half Speed)
while(1);
}// end of program
PIC 18F6722
Port C_2
Port B_6
Port B_7
Controller
CCP1-out
Driver IC
#include <18F6722.h>
#use delay(clock=4000000) //clock 4Mhz frequency
int16 duty_cycle; // since the value has 10bit
int i;
main() {
// PWM Configurations
setup_timer_2(T2_DIV_BY_1,255,1); // Set PWM frequency
setup_ccp1(CCP_PWM); // Configure CCP1 to PWM mode
set_pwm1_duty(1023L); // default duty cycle = 100% (Full Speed)
//
while(1){
output_low(PIN_B6); // set one direction-clock wise
output_high(PIN_B7);
delay_ms(5000);
output_high(PIN_B6); // set anticlock wise direction
output_low(PIN_B7);
}
}// end of program
Example: As shown in Figure below, the automated drilling machine with conveyor belt is
required to stop the motor for two seconds during drilling the plot.
Suppose, plate position is detected with proximity sensor, and then clamp comes down to
hold the plate and driller activated for two seconds. During this process, motor/conveyor
belt suppose to be stopped.
Use PIC18F6722 and develop application real-time.
Example:
Write a PIC C program to detect the one key at a time and
display that pressed key number on LCD display. Use 4*4
key pad.
Solution:
Let, Matrix Keypad is connected to the PORT-A and
PORT - C of the PIC Microcontroller as follows
// Pin Assignment
// pin a2 ..... col 1
// pin a3 ..... col 2
// pin a4 ..... col 3
// pin a5 ..... col 4
// pin c0 ..... row 1
// pin c1 ..... row 2
// pin c2 ..... row 3
// pin c3 ..... row 4
//
//
//
//
//
//
//
//
int read_keypad(void)
{ output_a(0x00); // clear the ports
output_c(0x00);
while(1) // Loop to infinity
{
output_high(PIN_a2); // first column high for scanning purposes
if(input(PIN_c0)) // if row 1 goes high then
{while (input(pin_c0));
return(1); // key being pressed is one
}
else if(input(PIN_c1)) // if row 2 goes high then
{while (input(pin_c1));
return(5); // key being pressed is four
}
else if(input(PIN_c2)) // if row 3 goes high then
{while (input(pin_c2));
return(9); // key being pressed is seven
}
else if(input(PIN_c3)) // if row 4 goes high then
{while (input(pin_c3));
return(13); // key being pressed is ten
}
output_a(0x00); // Clear Port A
10
11
12
14
15
13
Rows
As inputs
Sources: http://www.electrosome.com/
USART
USART: Universal Synchronous Asynchronous Receiver
Transmitter (USART) module is a serial I/O communication
peripheral unit
Modern version: called somewhat differently EUSART:
Enhanced Universal Synchronous Asynchronous Receiver
Transmitter
Also known as Serial Communications Interface (SCI)
Contains all clock generators, shift registers and data buffers
necessary to perform an input/output serial data transfer
independently
Clock for synchronization, this module can also establish
Asynchronous connection, Some of the applications: like, radio or
infrared remote control using asynchronous transmission for data
transfer
Master Synchronous Serial Port (MSSP) module is a serial interface, useful for
communicating with other peripheral or microcontroller devices
Two MSSP modules: MSSP1 and MSSP2, each operates independently
Each MSSP module consists of a transmit/receive shift register (SSPxSR) and a
buffer register (SSPxBUF)
SSPxSR shifts the data in and out of the device, MSb first.
SSPxBUF holds the data that was written to the SSPxSR until the received data
is ready.
Once the 8 bits of data have been received, that byte is moved to the SSPxBUF
register. Then, the Buffer Full detect bit, BF (SSPxSTAT<0>) and the interrupt
flag bit, SSPxIF, are set.
Double-buffering of the received data (SSPxBUF) allows the next byte to start
reception before reading the data that was just received
Write Collision Detect bit, WCOL (SSPxCON1<7>), will be set if any write to
the SSPxBUF register during transmission/reception of data will be ignored.
The Buffer Full bit, BF (SSPxSTAT<0>), indicates when SSPxBUF has been
loaded with the received data (transmission is complete).
When the SSPxBUF is read, the BF bit is cleared.
MAX232
The bit period is set by the baud rate. A typical value is 9600
baud, which is about 10 k bits per second
SPI clock rate (bit rate) is user programmable to be one of the following:
FOSC/4 (or TCY)
FOSC/16 (or 4 TCY)
FOSC/64 (or 16 TCY)
Timer2 output/2
Allows a maximum data rate (at 40 MHz) of 10.00 Mbps
It can take Two character FIFO memory (first in, first-out) which
allows reception of two characters simultaneously
Example:
Wireless communication through Serial Input/Output pins (TX and RX)
- Sample diagram with PIC16F877 for Temperature Display with wireless communication
Tx Pin
Rx Pin
main(){
int s;
lcd_init();
//lcd initilised
lcd_putc('\f');
//lcd is cleared
lcd_gotoxy(1,1);
//move cursor
lcd_putc("___Temp:");
//print this statement "___Temp:"
lcd_gotoxy(15,1);
//move cursor
lcd_putc("__");
//print this statement "__"
while(1){
s = getc();
//get the value sent from transmitter
temp1 = s * 0.4887;
// value in s is converted to actual temperature
lcd_gotoxy(9,1);
//move cursor
printf(lcd_putc, "%2.1f'C", temp2); //display temp. Rx from Tx and display on lcd
}}