SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler offline
Microcontroller Lab.
Eng.Khaled Tamziz
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 1
PPU IUT Cachan
Mechanical Department
Mechatronic
Timers and PWM
Bibliography
Microcontroller PIC18F4550 Data Sheet
39632c.pdf - Chapters 11 to 15
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 2
MPLAB_C18 libraries documentation
MPLAB_C18_Libraries_51297f.pdf - Chapters 2.7 and 2.9
MPLAB_C18 header files
timers.h and pwm.h
MPLAB_C18 C source files
mcc18srctraditionnalpmc
Introduction
• In this course, we will talk about :
– Timers
– DC motor speed control (shortly)
– Pulse width modulation
– Basic state machine diagrams
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 3
– Basic state machine diagrams
Timers
• 4 timers are available :
– Timer0
– Timer1
– Timer2
– Timer3
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 4
• Each of them has general and special features.
• We will study general features.
• Then we’ll use special features with Timer2.
• It is necessary to understand the microcontroller
data sheet to be able to use the C hardware libraries.
Basic timer block diagram
8 or 16-bit counterClock
TMRxON bit
TMRxIF bit
set on
overflow
---
cleared by
software
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 5
Clock selection
Multiplexer
Programmable Prescaler
Sync with internal clock
Internal
or
external
clock
sources
software
Microcontroller internal data bus
read or write
the counter
register
.
.
.
Timers configuration and use
• C18 timers libraries allow :
– to access configuration registers and start the timer
(OpenTimerx functions).
– to read the value of the counter register
(ReadTimerx functions).
– to write a new value to the counter register
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 6
– to write a new value to the counter register
(WriteTimerx functions).
– to stop the timer (CloseTimerx functions).
• To test overflow, we need to read TMRxIF bit directly
in its own register.
• The Microcontroller Data Sheet gives information
about the concerned registers.
Rotation measurement
signal
LEFT_ENCODER
R1 R2
VCC
4
31
2
U3
H21A1
VCC
Simplified schematic
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 7
time
Each edge corresponds to a rotation of a known angle of the axis of the motor.
We know the reducer rate and the diameter of the wheel, so it is possible to calculate
the distance accomplished by the robot.
We have to count edges : we ‘ll use a timer with an external clock.
Example : use of Timer1 to count events
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 8
Configure and start Timer1
OpenTimer1(
TIMER_INT_OFF &
T1_16BIT_RW &
T1_SOURCE_EXT &
T1_PS_1_1 &
T1_OSC1EN_OFF &
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 9
T1_OSC1EN_OFF &
T1_SYNC_EXT_OFF
);
Disable the interrupt generation from
Timer1. We will see this later.
Use Timer1 as a 16-bit counter.
Select an external clock.
Choose the prescale value.
Disable the internal Timer1 oscillator.
Disable the synchronization with the
processor clock.
Then, clear the counter register, clear TMR1IF and start the timer.
Read and write the Timer1 value
• Read the value :
– prototype
unsigned int ReadTimer1( void );
– code example
unsigned int result;
result = ReadTimer1();
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 10
• Write a new value :
– prototype
void WriteTimer1( unsigned int timer );
– code example
WriteTimer1(0);
Test the Timer1 overflow
• TMR1IF is the bit 0 of PIR1 register.
• Code example :
if (PIR1bits.TMR1IF != 0) {
// timer1 overflow detected
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 11
// timer1 overflow detected
PIR1bits.TMR1IF = 0; // reset flag
}
Timer2 special features
• Timer2 is an 8-bit counter.
• The values of TMR2 and PR2 are compared on each clock cycle.
• When the two values are equal, the comparator generates an output
signal.
• This signal also resets the value of TMR2 to 00h on the next cycle
and drives the output counter/postscaler.
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 12
DC motor speed control
• First, we assume the motor speed depends on the average voltage. Thus,
we need to change the average voltage on the motor.
• The power electronics block contains a H-Bridge designed for motion
Power electronics
DC
motor
sign
pwm
POWER
Vmotor
from
microcontroller
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 13
• The power electronics block contains a H-Bridge designed for motion
control applications.
• The signal sign controls the direction of the rotation.
• The signal pwm controls the average voltage on the motor.
0
1
t
T
α.T
(1 - α).T
pwm
– T is the period.
– The duty cycle (α) is generally given in percent.
– The average value is α.
– For a power supply of U volts, Vmotor = α.U.
Capture/Compare/PWM (CCP) Modules
• Two CCP modules are available (CCP1 and CCP2).
• In PWM mode, the two modules use Timer2 as a time base.
Thus PWM frequency is the same for CCP1 and CCP2.
• Each module has its own duty cycle.
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 14
PWM period and duty cycle
• The main trap is that the PWM period is set by a 8-bit
value and the duty cycle is controlled by a 10-bit
value.
• Example :
– let’s assume the period value is 99, thus the TMR2
value (8-bit value) should grow from 0 to (99+1) = 100
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 15
value (8-bit value) should grow from 0 to (99+1) = 100
(reset value)
– so the TMR2 extended value (10-bit value) should
grow from 0 to (99+1) * 4 = 400
– and then the duty cycle value should vary from 0 (0%
duty cycle) to 400 (100% duty cycle).
PWM configuration and use
• C18 timers libraries allow :
– to configure Timer2 (OpenTimer2 function).
– to configure CCPx (OpenPWMx functions).
– to set the duty cycle (SetDCPWMx functions).
– to stop the PWM (ClosePWMx functions).
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 16
• The pins concerned must be configured as outputs
– by setting the appropriate TRIS register bit
– or by using SetOutputPWMx functions.
Example
• Let’s assume that we need a 20kHz PWM period.
– On our board, Fosc = 48MHz thus Fosc/4 = 12MHz.
– To have a full resolution (10-bit) we must choose the
biggest value for the 8-bit period register.
– If we choose 0xFF, the clock frequency will be divided
by 256 to obtain the Timer2 frequency.
– Now, we are able to calculate the prescaler :
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 17
– Now, we are able to calculate the prescaler :
(12.106 / 256) / 20000 = 2.34 < 4
– We have to reverse the calculus with a prescale value
of 4 and we’ll find the period register value :
PR2 = (12.106 / 4) / 20000 – 1 = 149
– Thus the duty cycle should be between 0 and 600.
Code example
#include <timers.h>
#include <pwm.h>
…
OpenTimer2( // Timer2 configuration
TIMER_INT_OFF & // No interrupt
T2_PS_1_4 & // Prescale 1:4
T2_POST_1_1 // Don’t use postscaler actually
);
OpenPWM1(149); // Use of CCP1 as PWM module
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 18
OpenPWM1(149); // Use of CCP1 as PWM module
OpenPWM2(149); // Use of CCP2 as PWM module
SetDCPWM1(0); // Set 0% duty cycle to PWM1
SetDCPWM2(0); // Set 0% duty cycle to PWM2
TRISCbits.TRISC2 = 0; // Make RC2 (PWM1) an output
TRISCbits.TRISC1 = 0; // Make RC1 (PWM2) an output
…
SetDCPWM1(150); // Set 25% duty cycle to PWM1
SetDCPWM2(450); // Set 75% duty cycle to PWM2
…
State machine
• We will use state machine diagram to program
sequential comportment of the robot.
• We will translate the diagram into C language by
using switch/case statements.
• We will study an example to understand clearly the
principles.
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 19
principles.
• We would like the two wheels to cover the same
distance.
• The simplest way to do it is exposed on the next
slide.
Example of state machine diagram
0
1
set the distance to cover
BP0 pushed
two motors on
left
distance
done
right
distance
done
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 20
32 left motor onright motor on
right
distance
done
left
distance
done
Code example
…
void main(void)
{
//local variables definition and initialization
unsigned char State = 0; // Store the actual state
char Bp0; // Store 1 if BP0 is pushed
unsigned int LeftEncoder, // Store Timer1 value
RightEncoder, // Store Timer0 value
Distance; // Store "distance" to cover
//peripheral configuration
…
while(1) { // main loop
Bp0 = !(PORTBbits.RB3); // Read BP0 status
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 21
Bp0 = !(PORTBbits.RB3); // Read BP0 status
RightEncoder = ReadTimer0(); // Read right encoder value
LeftEncoder = ReadTimer1(); // Read left encoder value
switch (State) { // State machine
case 0 : // State 0
SetDCPWM1(0); // Set 0% duty cycle to left pwm
SetDCPWM2(0); // Set 0% duty cycle to right pwm
if (Bp0) { // BP0 is pushed
State = 1; // Go to State 1
WriteTimer0(0); // Reset encoders
WriteTimer1(0);
Distance = 1000; // Set distance to cover
}
break; // end case 0
case 1 :
SetDCPWM1(150); // Set 25% duty cycle to left pwm
SetDCPWM2(150); // Set 25% duty cycle to right pwm
if (LeftEncoder >= Distance) {
// Left wheel covers the distance
State = 2; // Go to State 2
} else if (RightEncoder >= Distance) {
// Right wheel covers the distance
State = 3; // Go to State 3
}
break; // end case 1
case 2 :
SetDCPWM1(0); // Set 0% duty cycle to left pwm
SetDCPWM2(150); // Set 25% duty cycle to right pwm
if (RightEncoder >= Distance) {
// Right wheel covers the distance
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 22
// Right wheel covers the distance
State = 0; // Go to State 0
}
break; // end case 2
case 3 :
SetDCPWM1(150); // Set 25% duty cycle to left pwm
SetDCPWM2(0); // Set 0% duty cycle to right pwm
if (LeftEncoder >= Distance) {
// Left wheel covers the distance
State = 0; // Go to State 0
}
break; // end case 3
} // end switch
} // end while
} // end main
Conclusion
• We have learnt
– how to use Timers
– how to control the speed of a DC motor
– how to generate PWM signals
– how to program a simple state machine
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 23
• We’ll use this knowledge
– to manage with distance measurement
– to control the speed of the robot
– to run a special trajectory
Now, practice
• Use timer1 to count events on left encoder
• Use timer0 to count events on right encoder
• Change speed of motors using PWM
• The robot covers a circle shaped trajectory
• The robot covers a house shaped trajectory
Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 24

Mais conteúdo relacionado

Mais procurados

Embedded System Programming on ARM Cortex M3 and M4 Course
Embedded System Programming on ARM Cortex M3 and M4 CourseEmbedded System Programming on ARM Cortex M3 and M4 Course
Embedded System Programming on ARM Cortex M3 and M4 CourseFastBit Embedded Brain Academy
 
INTERRUPTS OF 8086 MICROPROCESSOR
INTERRUPTS OF 8086 MICROPROCESSORINTERRUPTS OF 8086 MICROPROCESSOR
INTERRUPTS OF 8086 MICROPROCESSORGurudev joshi
 
Arm architecture chapter2_steve_furber
Arm architecture chapter2_steve_furberArm architecture chapter2_steve_furber
Arm architecture chapter2_steve_furberasodariyabhavesh
 
ARM - Advance RISC Machine
ARM - Advance RISC MachineARM - Advance RISC Machine
ARM - Advance RISC MachineEdutechLearners
 
Byte and string manipulation 8086
Byte and string manipulation 8086Byte and string manipulation 8086
Byte and string manipulation 8086mpsrekha83
 
Arm modes
Arm modesArm modes
Arm modesabhi165
 
How to create SystemVerilog verification environment?
How to create SystemVerilog verification environment?How to create SystemVerilog verification environment?
How to create SystemVerilog verification environment?Sameh El-Ashry
 
Interrupt in real time system
Interrupt in real time system Interrupt in real time system
Interrupt in real time system ali jawad
 
8086-instruction-set-ppt
 8086-instruction-set-ppt 8086-instruction-set-ppt
8086-instruction-set-pptjemimajerome
 
Introduction to arm architecture
Introduction to arm architectureIntroduction to arm architecture
Introduction to arm architectureZakaria Gomaa
 
Computer architecture instruction formats
Computer architecture instruction formatsComputer architecture instruction formats
Computer architecture instruction formatsMazin Alwaaly
 
Introduction to FreeRTOS
Introduction to FreeRTOSIntroduction to FreeRTOS
Introduction to FreeRTOSICS
 

Mais procurados (20)

Embedded System Programming on ARM Cortex M3 and M4 Course
Embedded System Programming on ARM Cortex M3 and M4 CourseEmbedded System Programming on ARM Cortex M3 and M4 Course
Embedded System Programming on ARM Cortex M3 and M4 Course
 
INTERRUPTS OF 8086 MICROPROCESSOR
INTERRUPTS OF 8086 MICROPROCESSORINTERRUPTS OF 8086 MICROPROCESSOR
INTERRUPTS OF 8086 MICROPROCESSOR
 
Arm architecture
Arm architectureArm architecture
Arm architecture
 
Arm architecture chapter2_steve_furber
Arm architecture chapter2_steve_furberArm architecture chapter2_steve_furber
Arm architecture chapter2_steve_furber
 
ARM Processors
ARM ProcessorsARM Processors
ARM Processors
 
ARM - Advance RISC Machine
ARM - Advance RISC MachineARM - Advance RISC Machine
ARM - Advance RISC Machine
 
Byte and string manipulation 8086
Byte and string manipulation 8086Byte and string manipulation 8086
Byte and string manipulation 8086
 
Arm modes
Arm modesArm modes
Arm modes
 
How to create SystemVerilog verification environment?
How to create SystemVerilog verification environment?How to create SystemVerilog verification environment?
How to create SystemVerilog verification environment?
 
Interrupt in real time system
Interrupt in real time system Interrupt in real time system
Interrupt in real time system
 
8086-instruction-set-ppt
 8086-instruction-set-ppt 8086-instruction-set-ppt
8086-instruction-set-ppt
 
Introduction to arm architecture
Introduction to arm architectureIntroduction to arm architecture
Introduction to arm architecture
 
itft-Clock generator
itft-Clock generatoritft-Clock generator
itft-Clock generator
 
Memory model
Memory modelMemory model
Memory model
 
Assembly language
Assembly languageAssembly language
Assembly language
 
Computer architecture instruction formats
Computer architecture instruction formatsComputer architecture instruction formats
Computer architecture instruction formats
 
Introduction to FreeRTOS
Introduction to FreeRTOSIntroduction to FreeRTOS
Introduction to FreeRTOS
 
8086
80868086
8086
 
LCD Interacing with 8051
LCD Interacing with 8051LCD Interacing with 8051
LCD Interacing with 8051
 
Unit 2 mpmc
Unit 2 mpmcUnit 2 mpmc
Unit 2 mpmc
 

Semelhante a Lecture 2 timers, pwm, state machine IN PIC

Program, Code of Program and Screen Shot of Output (UNIVERSAL DRIVER USING µ...
Program, Code of Program and  Screen Shot of Output (UNIVERSAL DRIVER USING µ...Program, Code of Program and  Screen Shot of Output (UNIVERSAL DRIVER USING µ...
Program, Code of Program and Screen Shot of Output (UNIVERSAL DRIVER USING µ...Er. Ashish Pandey
 
Assembly programming II
Assembly programming IIAssembly programming II
Assembly programming IIOmar Sanchez
 
Assembly programming II
Assembly programming IIAssembly programming II
Assembly programming IIOmar Sanchez
 
Assembly programming II
Assembly programming IIAssembly programming II
Assembly programming IIOmar Sanchez
 
Lecture on PIC-1.pptx
Lecture on PIC-1.pptxLecture on PIC-1.pptx
Lecture on PIC-1.pptxgodfrey35
 
Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]
Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]
Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]akmalKhan55
 
Enhanced phase width modulation in TMS320F28335D
Enhanced phase width modulation in TMS320F28335DEnhanced phase width modulation in TMS320F28335D
Enhanced phase width modulation in TMS320F28335DSatya Sahoo
 
Design and development of programmable controller for air sampling machine
Design and development of programmable controller for air sampling machineDesign and development of programmable controller for air sampling machine
Design and development of programmable controller for air sampling machineeSAT Journals
 
bidirectional report
bidirectional reportbidirectional report
bidirectional reportHasan baig
 
Advanced insrumentation lab manual
Advanced insrumentation lab manualAdvanced insrumentation lab manual
Advanced insrumentation lab manualGautam sai teza
 

Semelhante a Lecture 2 timers, pwm, state machine IN PIC (20)

Timer 2 concept
Timer 2 conceptTimer 2 concept
Timer 2 concept
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
PLC.pdf
PLC.pdfPLC.pdf
PLC.pdf
 
Program, Code of Program and Screen Shot of Output (UNIVERSAL DRIVER USING µ...
Program, Code of Program and  Screen Shot of Output (UNIVERSAL DRIVER USING µ...Program, Code of Program and  Screen Shot of Output (UNIVERSAL DRIVER USING µ...
Program, Code of Program and Screen Shot of Output (UNIVERSAL DRIVER USING µ...
 
chapter 4
chapter 4chapter 4
chapter 4
 
Assembly programming II
Assembly programming IIAssembly programming II
Assembly programming II
 
Assembly programming II
Assembly programming IIAssembly programming II
Assembly programming II
 
Assembly programming II
Assembly programming IIAssembly programming II
Assembly programming II
 
Lecture on PIC-1.pptx
Lecture on PIC-1.pptxLecture on PIC-1.pptx
Lecture on PIC-1.pptx
 
Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]
Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]
Share 'speed control_of_dc_motor_using_microcontroller.pptx'[1][1]
 
Enhanced phase width modulation in TMS320F28335D
Enhanced phase width modulation in TMS320F28335DEnhanced phase width modulation in TMS320F28335D
Enhanced phase width modulation in TMS320F28335D
 
Timers and pwm
Timers and pwmTimers and pwm
Timers and pwm
 
Ccp
CcpCcp
Ccp
 
Timers and Endge-aligned PWM
Timers and Endge-aligned PWMTimers and Endge-aligned PWM
Timers and Endge-aligned PWM
 
Design and development of programmable controller for air sampling machine
Design and development of programmable controller for air sampling machineDesign and development of programmable controller for air sampling machine
Design and development of programmable controller for air sampling machine
 
Week7_lpm_2015.ppt
Week7_lpm_2015.pptWeek7_lpm_2015.ppt
Week7_lpm_2015.ppt
 
PLC PPT.ppt
PLC PPT.pptPLC PPT.ppt
PLC PPT.ppt
 
bidirectional report
bidirectional reportbidirectional report
bidirectional report
 
Advanced insrumentation lab manual
Advanced insrumentation lab manualAdvanced insrumentation lab manual
Advanced insrumentation lab manual
 
ie450pp10.ppt
ie450pp10.pptie450pp10.ppt
ie450pp10.ppt
 

Mais de أشرف أمجد الشريف (11)

Single phase im-lecture_10_1
Single phase im-lecture_10_1Single phase im-lecture_10_1
Single phase im-lecture_10_1
 
Sensors, Proximity sensors. Optical – Through-beam, Optical - Diffuse
Sensors, Proximity sensors. Optical – Through-beam, Optical - DiffuseSensors, Proximity sensors. Optical – Through-beam, Optical - Diffuse
Sensors, Proximity sensors. Optical – Through-beam, Optical - Diffuse
 
Lecture 4 i2 c bus & interrupts
Lecture 4   i2 c bus & interruptsLecture 4   i2 c bus & interrupts
Lecture 4 i2 c bus & interrupts
 
The Uses of Nanosensors: From Smart Dust to Nano “Mother Ships”
The Uses of Nanosensors: From Smart Dust to Nano “Mother Ships”The Uses of Nanosensors: From Smart Dust to Nano “Mother Ships”
The Uses of Nanosensors: From Smart Dust to Nano “Mother Ships”
 
Hydraulic pumps performance and Characteristics
Hydraulic pumps performance and CharacteristicsHydraulic pumps performance and Characteristics
Hydraulic pumps performance and Characteristics
 
Hydrolic Fluid purpose & properties (chapter 2)
Hydrolic Fluid purpose & properties (chapter 2)Hydrolic Fluid purpose & properties (chapter 2)
Hydrolic Fluid purpose & properties (chapter 2)
 
Lecture 4 i2 c bus & interrupts
Lecture 4   i2 c bus & interruptsLecture 4   i2 c bus & interrupts
Lecture 4 i2 c bus & interrupts
 
Lecture 3a analog to digital converter
Lecture 3a   analog to digital converterLecture 3a   analog to digital converter
Lecture 3a analog to digital converter
 
Lecture 1 microcontroller overview
Lecture 1   microcontroller overviewLecture 1   microcontroller overview
Lecture 1 microcontroller overview
 
Braking performance 4
Braking  performance 4Braking  performance 4
Braking performance 4
 
VEHICLE ROLLOVER ANALYSIS
VEHICLE ROLLOVER ANALYSISVEHICLE ROLLOVER ANALYSIS
VEHICLE ROLLOVER ANALYSIS
 

Último

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Último (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

Lecture 2 timers, pwm, state machine IN PIC

  • 1. Microcontroller Lab. Eng.Khaled Tamziz Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 1 PPU IUT Cachan Mechanical Department Mechatronic
  • 2. Timers and PWM Bibliography Microcontroller PIC18F4550 Data Sheet 39632c.pdf - Chapters 11 to 15 Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 2 MPLAB_C18 libraries documentation MPLAB_C18_Libraries_51297f.pdf - Chapters 2.7 and 2.9 MPLAB_C18 header files timers.h and pwm.h MPLAB_C18 C source files mcc18srctraditionnalpmc
  • 3. Introduction • In this course, we will talk about : – Timers – DC motor speed control (shortly) – Pulse width modulation – Basic state machine diagrams Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 3 – Basic state machine diagrams
  • 4. Timers • 4 timers are available : – Timer0 – Timer1 – Timer2 – Timer3 Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 4 • Each of them has general and special features. • We will study general features. • Then we’ll use special features with Timer2. • It is necessary to understand the microcontroller data sheet to be able to use the C hardware libraries.
  • 5. Basic timer block diagram 8 or 16-bit counterClock TMRxON bit TMRxIF bit set on overflow --- cleared by software Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 5 Clock selection Multiplexer Programmable Prescaler Sync with internal clock Internal or external clock sources software Microcontroller internal data bus read or write the counter register . . .
  • 6. Timers configuration and use • C18 timers libraries allow : – to access configuration registers and start the timer (OpenTimerx functions). – to read the value of the counter register (ReadTimerx functions). – to write a new value to the counter register Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 6 – to write a new value to the counter register (WriteTimerx functions). – to stop the timer (CloseTimerx functions). • To test overflow, we need to read TMRxIF bit directly in its own register. • The Microcontroller Data Sheet gives information about the concerned registers.
  • 7. Rotation measurement signal LEFT_ENCODER R1 R2 VCC 4 31 2 U3 H21A1 VCC Simplified schematic Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 7 time Each edge corresponds to a rotation of a known angle of the axis of the motor. We know the reducer rate and the diameter of the wheel, so it is possible to calculate the distance accomplished by the robot. We have to count edges : we ‘ll use a timer with an external clock.
  • 8. Example : use of Timer1 to count events Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 8
  • 9. Configure and start Timer1 OpenTimer1( TIMER_INT_OFF & T1_16BIT_RW & T1_SOURCE_EXT & T1_PS_1_1 & T1_OSC1EN_OFF & Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 9 T1_OSC1EN_OFF & T1_SYNC_EXT_OFF ); Disable the interrupt generation from Timer1. We will see this later. Use Timer1 as a 16-bit counter. Select an external clock. Choose the prescale value. Disable the internal Timer1 oscillator. Disable the synchronization with the processor clock. Then, clear the counter register, clear TMR1IF and start the timer.
  • 10. Read and write the Timer1 value • Read the value : – prototype unsigned int ReadTimer1( void ); – code example unsigned int result; result = ReadTimer1(); Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 10 • Write a new value : – prototype void WriteTimer1( unsigned int timer ); – code example WriteTimer1(0);
  • 11. Test the Timer1 overflow • TMR1IF is the bit 0 of PIR1 register. • Code example : if (PIR1bits.TMR1IF != 0) { // timer1 overflow detected Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 11 // timer1 overflow detected PIR1bits.TMR1IF = 0; // reset flag }
  • 12. Timer2 special features • Timer2 is an 8-bit counter. • The values of TMR2 and PR2 are compared on each clock cycle. • When the two values are equal, the comparator generates an output signal. • This signal also resets the value of TMR2 to 00h on the next cycle and drives the output counter/postscaler. Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 12
  • 13. DC motor speed control • First, we assume the motor speed depends on the average voltage. Thus, we need to change the average voltage on the motor. • The power electronics block contains a H-Bridge designed for motion Power electronics DC motor sign pwm POWER Vmotor from microcontroller Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 13 • The power electronics block contains a H-Bridge designed for motion control applications. • The signal sign controls the direction of the rotation. • The signal pwm controls the average voltage on the motor. 0 1 t T α.T (1 - α).T pwm – T is the period. – The duty cycle (α) is generally given in percent. – The average value is α. – For a power supply of U volts, Vmotor = α.U.
  • 14. Capture/Compare/PWM (CCP) Modules • Two CCP modules are available (CCP1 and CCP2). • In PWM mode, the two modules use Timer2 as a time base. Thus PWM frequency is the same for CCP1 and CCP2. • Each module has its own duty cycle. Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 14
  • 15. PWM period and duty cycle • The main trap is that the PWM period is set by a 8-bit value and the duty cycle is controlled by a 10-bit value. • Example : – let’s assume the period value is 99, thus the TMR2 value (8-bit value) should grow from 0 to (99+1) = 100 Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 15 value (8-bit value) should grow from 0 to (99+1) = 100 (reset value) – so the TMR2 extended value (10-bit value) should grow from 0 to (99+1) * 4 = 400 – and then the duty cycle value should vary from 0 (0% duty cycle) to 400 (100% duty cycle).
  • 16. PWM configuration and use • C18 timers libraries allow : – to configure Timer2 (OpenTimer2 function). – to configure CCPx (OpenPWMx functions). – to set the duty cycle (SetDCPWMx functions). – to stop the PWM (ClosePWMx functions). Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 16 • The pins concerned must be configured as outputs – by setting the appropriate TRIS register bit – or by using SetOutputPWMx functions.
  • 17. Example • Let’s assume that we need a 20kHz PWM period. – On our board, Fosc = 48MHz thus Fosc/4 = 12MHz. – To have a full resolution (10-bit) we must choose the biggest value for the 8-bit period register. – If we choose 0xFF, the clock frequency will be divided by 256 to obtain the Timer2 frequency. – Now, we are able to calculate the prescaler : Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 17 – Now, we are able to calculate the prescaler : (12.106 / 256) / 20000 = 2.34 < 4 – We have to reverse the calculus with a prescale value of 4 and we’ll find the period register value : PR2 = (12.106 / 4) / 20000 – 1 = 149 – Thus the duty cycle should be between 0 and 600.
  • 18. Code example #include <timers.h> #include <pwm.h> … OpenTimer2( // Timer2 configuration TIMER_INT_OFF & // No interrupt T2_PS_1_4 & // Prescale 1:4 T2_POST_1_1 // Don’t use postscaler actually ); OpenPWM1(149); // Use of CCP1 as PWM module Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 18 OpenPWM1(149); // Use of CCP1 as PWM module OpenPWM2(149); // Use of CCP2 as PWM module SetDCPWM1(0); // Set 0% duty cycle to PWM1 SetDCPWM2(0); // Set 0% duty cycle to PWM2 TRISCbits.TRISC2 = 0; // Make RC2 (PWM1) an output TRISCbits.TRISC1 = 0; // Make RC1 (PWM2) an output … SetDCPWM1(150); // Set 25% duty cycle to PWM1 SetDCPWM2(450); // Set 75% duty cycle to PWM2 …
  • 19. State machine • We will use state machine diagram to program sequential comportment of the robot. • We will translate the diagram into C language by using switch/case statements. • We will study an example to understand clearly the principles. Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 19 principles. • We would like the two wheels to cover the same distance. • The simplest way to do it is exposed on the next slide.
  • 20. Example of state machine diagram 0 1 set the distance to cover BP0 pushed two motors on left distance done right distance done Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 20 32 left motor onright motor on right distance done left distance done
  • 21. Code example … void main(void) { //local variables definition and initialization unsigned char State = 0; // Store the actual state char Bp0; // Store 1 if BP0 is pushed unsigned int LeftEncoder, // Store Timer1 value RightEncoder, // Store Timer0 value Distance; // Store "distance" to cover //peripheral configuration … while(1) { // main loop Bp0 = !(PORTBbits.RB3); // Read BP0 status Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 21 Bp0 = !(PORTBbits.RB3); // Read BP0 status RightEncoder = ReadTimer0(); // Read right encoder value LeftEncoder = ReadTimer1(); // Read left encoder value switch (State) { // State machine case 0 : // State 0 SetDCPWM1(0); // Set 0% duty cycle to left pwm SetDCPWM2(0); // Set 0% duty cycle to right pwm if (Bp0) { // BP0 is pushed State = 1; // Go to State 1 WriteTimer0(0); // Reset encoders WriteTimer1(0); Distance = 1000; // Set distance to cover } break; // end case 0
  • 22. case 1 : SetDCPWM1(150); // Set 25% duty cycle to left pwm SetDCPWM2(150); // Set 25% duty cycle to right pwm if (LeftEncoder >= Distance) { // Left wheel covers the distance State = 2; // Go to State 2 } else if (RightEncoder >= Distance) { // Right wheel covers the distance State = 3; // Go to State 3 } break; // end case 1 case 2 : SetDCPWM1(0); // Set 0% duty cycle to left pwm SetDCPWM2(150); // Set 25% duty cycle to right pwm if (RightEncoder >= Distance) { // Right wheel covers the distance Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 22 // Right wheel covers the distance State = 0; // Go to State 0 } break; // end case 2 case 3 : SetDCPWM1(150); // Set 25% duty cycle to left pwm SetDCPWM2(0); // Set 0% duty cycle to right pwm if (LeftEncoder >= Distance) { // Left wheel covers the distance State = 0; // Go to State 0 } break; // end case 3 } // end switch } // end while } // end main
  • 23. Conclusion • We have learnt – how to use Timers – how to control the speed of a DC motor – how to generate PWM signals – how to program a simple state machine Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 23 • We’ll use this knowledge – to manage with distance measurement – to control the speed of the robot – to run a special trajectory
  • 24. Now, practice • Use timer1 to count events on left encoder • Use timer0 to count events on right encoder • Change speed of motors using PWM • The robot covers a circle shaped trajectory • The robot covers a house shaped trajectory Project Pedagogy approach of Microcontroller – Palestinian Robotic Cup 24