Sismik 6 - Timer

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

PWM DAN TIMER

PULSE WIDTH MODULATION (PWM)


• Several modulation methods have been developed for
applications that require a digital representation of an
analog signal
• One popular and relevant scheme is pulse width
modulation (PWM) in which the instantaneous amplitude
of an analog signal is represented by the width of periodic
square wave.
• For example, consider the signals depicted in Fig. 7.1
3

Figure 7.1: An example analog signal and a pulse width modulated representation
4

• Notice, the PWM version of the signal has a fixed


frequency defining the point when a pulse begins.
• During the period of an individual pulse, the signal
remains high for an amount of time proportional to the
amplitude of the analog signal.
• Recall the duty cycle of a square wave is given by

• where 0 ≤ τ ≤ T is the amount of time a signal is non-zero


and T is the period of the square wave.
5

• Effectively, the pulse duty cycle represents a measure of


the analog signal amplitude
• Specifically, when the amplitude of a signal is at or below
some minimal voltage Vmin, the PWM pulses have a 0%
duty cycle.
• Similarly, when a signal is at or above some maximal
voltage Vmax, the PWM pulses have a 100% duty cycle.
• Ideally, when the amplitude of a signal is in between Vmin
and Vmax, the duty cycle of the PWM pulses is defined by
the linear relation

• where Vsig is the analog signal.


6

DEMODULATION
• Converting the square-wave signal to the desired analog
value is referred to as demodulation, and requires a
demodulator circuit to use the pulse widths as a measure
for the signal amplitude
• Consider the simple low-pass filter (LPF) shown in Fig.
7.2.

• Figure 7.2: A simple low-pass filter.


7

• determined by the choice of R and C using the

• It is a well-known result that if fm << fh << ft , then an


approximation of the original signal is recovered

• Here, fm is the maximum frequency of the analog


message signal, and ft is the frequency of the PWM
square-wave.
• Thus, the filter needs to be designed such that the highest
frequency of the desired analog signal is less than fh.
8

• In practice, most systems do not construct an explicit LPF


before the load, which is typically either inductive or
capacitive

• Instead, the natural frequency response of the load is


used to demodulate the PWM pulses directly.

• In either case, effectively the voltage of the original


message signal is delivered to the load via averaging over
the PWM pulses
9

MODULATION
• The remaining component to outputting an analog signal
from a digital microcontroller is to generate the
appropriate PWM waveform, a process referred to as
modulation; i.e, an analog message signal modulates the
square-wave carrier by altering its duty cycle
• Most microcontrollers provide at least one port that has
timer sub-circuitry capable of generating PWM signals on
a port pin
• Typically, one just needs to configure the square-wave
frequency and desired duty cycle via a couple of registers.
• When enabled, the port pin will output a PWM signal that
can be demodulated in order to provide an approximation
to an analog signal.
10

• In the case of the ATmega328P, there are two 8-bit timers


and one 16-bit timer, all of which are capable of
generating PWM outputs. The registers are listed in Sec.
7.3.

• Note, in the init() function within the Wiring library, all three
timers are pre-initialized with some specific functionality in
mind. In particular, the often used delay() function relies
on a timer 0 interrupt, and so we will avoid using it for the
time being.
11

• On the ATmega328P, three waveform generation bits exist


within the two timer/counter control registers. Four of the
eight possible waveform generation modes involve PWM
waveform outputs, two of which are considered fast PWM
while the remaining two are called phase-correct PWM.
Shown in Fig. 7.3 and Fig. 7.4 are the four different output
waveforms given the specified waveform configurations.
12
13

ARDUINO PWM
• Pulse Width Modulation, or PWM, is a technique for
getting analog results with digital means. Digital control is
used to create a square wave, a signal switched between
on and off. This on-off pattern can simulate voltages in
between full on (5 Volts) and off (0 Volts) by changing the
portion of the time the signal spends on versus the time
that the signal spends off. The duration of "on time" is
called the pulse width. To get varying analog values, you
change, or modulate, that pulse width. If you repeat this
on-off pattern fast enough with an LED for example, the
result is as if the signal is a steady voltage between 0 and
5v controlling the brightness of the LED.
14

In the graphic below, the green lines represent a


regular time period. This duration or period is the
inverse of the PWM frequency. In other words, with
Arduino's PWM frequency at about 500Hz, the
green lines would measure 2 milliseconds each. A
call to analogWrite() is on a scale of 0 - 255, such
that analogWrite(255) requests a 100% duty cycle
(always on), and analogWrite(127) is a 50% duty
cycle (on half the time) for example.
15
16

PWM dapat diimplementasikan dengan


beberapa cara
• Briefly, a PWM signal is a digital square wave, where the
frequency is constant, but that fraction of the time the
signal is on (the duty cycle) can be varied between 0 and
100%
17

Aplikasi PWM
PWM has several uses:

• Dimming an LED
• Providing an analog output; if the digital output is filtered,
it will provide an analog voltage between 0% and 100% .
• Generating audio signals.
• Providing variable speed control for motors.
• Generating a modulated signal, for example to drive an
infrared LED for a remote control.
18

Simple Pulse Width Modulation with


analogWrite
The Arduino's programming language makes PWM easy to
use; simply call analogWrite(pin, dutyCycle), where
dutyCycle is a value from 0 to 255, and pin is one of the
PWM pins (3, 5, 6, 9, 10, or 11). The analogWrite function
provides a simple interface to the hardware PWM, but
doesn't provide any control over frequency. (Note that
despite the function name, the output is a digital signal,
often referred to as a square wave.) Probably 99% of the
readers can stop here, and just use analogWrite, but there
are other options that provide more flexibility.
19

Implementasi PWM secara manual

You can "manually" implement PWM on any pin by


repeatedly turning the pin on and off for the desired times.
e.g.
20

• This technique has the advantage that it can use any


digital output pin. In addition, you have full control the duty
cycle and frequency. One major disadvantage is that any
interrupts will affect the timing, which can cause
considerable jitter unless you disable interrupts. A second
disadvantage is you can't leave the output running while
the processor does something else. Finally, it's difficult to
determine the appropriate constants for a particular duty
cycle and frequency unless you either carefully count
cycles, or tweak the values while watching an
oscilloscope.
21

Using the ATmega PWM registers


directly
• The ATmega168P/328P chip has three PWM timers,
controlling 6 PWM outputs. By manipulating the chip's
timer registers directly, you can obtain more control than
the analogWrite function provides.
• The AVR ATmega328P datasheet provides a detailed
description of the PWM timers, but the datasheet can be
difficult to understand, due to the many different control
and output modes of the timers.
22

The Atmega 168/328 timers


• The ATmega328P has three timers known as
Timer 0, Timer 1, and Timer 2. Each timer has
two output compare registers that control the
PWM width for the timer's two outputs: when the
timer reaches the compare register value, the
corresponding output is toggled. The two outputs
for each timer will normally have the same
frequency, but can have different duty cycles
(depending on the respective output compare
register).
23

The first parameter I'll discuss is the speed at


which the timer increments the counter. The
Arduino clock runs at 16MHz, this is the fastest
speed that the timers can increment their
counters. At 16MHz each tick of the counter
represents 1/16,000,000 of a second (~63ns), so a
counter will take 10/16,000,000 seconds to reach a
value of 9 (counters are 0 indexed), and
100/16,000,000 seconds to reach a value of 99.
24

In many situations, you will find that setting the counter


speed to 16MHz is too fast. Timer0 and timer2 are 8
bit timers, meaning they can store a maximum counter
value of 255. Timer1 is a 16 bit timer, meaning it can
store a maximum counter value of 65535. Once a
counter reaches its maximum, it will tick back to zero
(this is called overflow). This means at 16MHz, even if
we set the compare match register to the max counter
value, interrupts will occur every 256/16,000,000
seconds (~16us) for the 8 bit counters, and every
65,536/16,000,000 (~4 ms) seconds for the 16 bit
counter. Clearly, this is not very useful if you only want
to interrupt once a second.
25

• Instead you can control the speed of the timer counter


incrementation by using something called a prescaler. A
prescaler dictates the speed of your timer according the
the following equation:

(timer speed (Hz)) = (Arduino clock speed (16MHz)) /


prescaler

So a 1 prescaler will increment the counter at 16MHz, an


8 prescaler will increment it at 2MHz, a 64 prescaler =
250kHz, and so on. As indicated in the tables above, the
prescaler can equal 1, 8, 64, 256, and 1024. (I'll explain
the meaning of CS12, CS11, and CS10 in the next step.)
26

• Now you can calculate the interrupt frequency with the


following equation:

interrupt frequency (Hz) = (Arduino clock speed


16,000,000Hz) / (prescaler * (compare match register + 1))
the +1 is in there because the compare match register is zero
indexed

rearranging the equation above, you can solve for the compare
match register value that will give your desired interrupt
frequency:

compare match register = [ 16,000,000Hz/ (prescaler *


desired interrupt frequency) ] - 1
remember that when you use timers 0 and 2 this number must
be less than 256, and less than 65536 for timer1
27

so if you wanted an interrupt every second


(frequency of 1Hz):
compare match register = [16,000,000 / (prescaler
* 1) ] -1
with a prescaler of 1024 you get:
compare match register = [16,000,000 / (1024 * 1)
] -1
= 15,624
since 256 < 15,624 < 65,536, you must use timer1
for this interrupt.
28

• The timers can also generate interrupts on overflow


and/or match against either output compare register, but
that's beyond the scope of this article.

• Timer Registers
• Several registers are used to control each timer. The
Timer/Counter Control Registers TCCRnA and TCCRnB
hold the main control bits for the timer. (Note that
TCCRnA and TCCRnB do not correspond to the outputs A
and B.) These registers hold several groups of bits:
29

• Waveform Generation Mode bits (WGM): these control


the overall mode of the timer.
(These bits are split between TCCRnA and TCCRnB.)
• Clock Select bits (CS): these control the clock prescaler
• Compare Match Output A Mode bits (COMnA): these
enable/disable/invert output A
• Compare Match Output B Mode bits (COMnB): these
enable/disable/invert output B
• The Output Compare Registers OCRnA and OCRnB set
the levels at which outputs A and B will be affected. When
the timer value matches the register value, the
corresponding output will be modified as specified by the
mode.

• The bits are slightly different for each timer, so consult the
datasheet for details. Timer 1 is a 16-bit timer and has
additional modes. Timer 2 has different prescaler values.
30

Manfaat Timer
Perhatikan program berikut

classic example is turning a relay on for 10 minutes. The 'delay'-way looks like
this:

int pin = 13;

void setup()
{
pinMode(13, OUTPUT);
digitalWrite(pin, HIGH);
delay(10 * 60 * 1000);
digitalWrite(pin, LOW);
}

void loop()
{
}
31

• The disadvantage of the delay approach is that nothing


else can go on while the 'delay' is happening. You cannot
update a display, or check for key presses for example.
32

Menyalakan lampu 10 menit menggunakan timer


#include "Timer.h"

Timer t;
int pin = 13;

void setup()
{
pinMode(pin, OUTPUT);
t.pulse(pin, 10 * 60 * 1000, HIGH); // 10 minutes
}

void loop()
{
t.update(); //This will service all the events associated with the timer.
}
33

Contoh program 2 timer


• One to flash an LED and another that reads A0 and
displays the result in the Serial Monitor.
34

• #include "Timer.h"

• Timer t;
• int pin = 13;
• void setup()
• {
• Serial.begin(9600);
• pinMode(pin, OUTPUT);
• t.oscillate(pin, 100, LOW); // Toggle pin 13 selama 100 ms dg nilai awal LOW
• //This will cause the LED to toggle state every 100 milliseconds.
• t.every(1000, takeReading);//Jalankan takeReading setiap 1 s
• }
• void loop()
• {
• t.update(); //This will service all the events associated with the timer
• }
• void takeReading()
• {
• Serial.println(analogRead(0));
• }
35

Beberapa perintah Arduino


int every(long period, callback)
Run the 'callback' every 'period' milliseconds.
Returns the ID of the timer event.

int every(long period, callback, int repeatCount)


Run the 'callback' every 'period' milliseconds for a
total of 'repeatCount' times. Returns the ID of the
timer event.

int after(long period, callback)


Run the 'callback' once after 'period' milliseconds.
Returns the ID of the timer event.
36

• int oscillate(int pin, long period, int startingValue)


• Toggle the state of the digital output 'pin' every 'period'
milliseconds. The pin's starting value is specified in
'startingValue', which should be HIGH or LOW. Returns
the ID of the timer event.

• int oscillate(int pin, long period, int startingValue, int


repeatCount)
• Toggle the state of the digital output 'pin' every 'period'
milliseconds 'repeatCount' times. The pin's starting value
is specified in 'startingValue', which should be HIGH or
LOW. Returns the ID of the timer event.
37

• int pulse(int pin, long period, int startingValue)


• Toggle the state of the digital output 'pin' just once after 'period'
milliseconds. The pin's starting value is specified in
'startingValue', which should be HIGH or LOW. Returns the ID
of the timer event.

• int stop(int id)


• Stop the timer event running. Returns the ID of the timer event.

• int update()
• Must be called from 'loop'. This will service all the events
associated with the timer
38

Menghentikan kejadian
#include "Timer.h"

Timer t;

int ledEvent;

void setup()
{
Serial.begin(9600);
int tickEvent = t.every(2000, doSomething);
Serial.print("2 second tick started id=");
Serial.println(tickEvent);

pinMode(13, OUTPUT);
ledEvent = t.oscillate(13, 50, HIGH);
Serial.print("LED event started id=");
Serial.println(ledEvent);

int afterEvent = t.after(10000, doAfter); //Jalankan doAfter setelah 10 s


Serial.print("After event started id=");
Serial.println(afterEvent);
}
39

void loop()
{
t.update();
}

void doSomething()
{
Serial.print("2 second tick: millis()=");
Serial.println(millis());
}

void doAfter()
{
Serial.println("stop the led event");
t.stop(ledEvent);
t.oscillate(13, 500, HIGH, 5); //Toggle ke pin 13 selama 500ms dimulai dg HIGH
//sebanyak 5 x
}
40

• Each of the events has an integer ID associated with it, so


that you can stop an event, as we do in this example
below, which will write to the serial monitor every 2
seconds, flash the LED and after 5 seconds, stop the LED
flashing fast, and flash it 5 times slowly.
41

Timer Frekuensi
Untuk menghitung frekuensi timer dengan frekuensi yang
ditentukan dapat dilakukan dengan cara sebagai berikut.
Menentukan frekuensi pembagi, misal 2 Hz
• Mengetahui frekuensi kerja Arduino, yakni 16 MHz
• Mengetahui prescaler timer, 256 untuk 8 bit, 65536 untuk 16
bit
• Membagi nilai frekuensi kerja Arduino (16 MHz) dengan
prescaler (256), hingga diperoleh hasil 62500
• Membagi hasil tersebut (62500) dengan frekuensi ditentukan (2
Hz), hingga diperoleh hasil 31250
• Memastikan bahwa hasil tersebut dapat digunakan dengan
membandingkannya nilai maximum prescaler, bila nilai tersebut
lebih kecil (dalam hal ini 31250 lebih kecil dari 65536), maka
hasilnya tersebut valid, bila tidak valid gunakan nilai prescaler
yang lebih besar
compare match register = [ 16,000,000Hz/
(prescaler * desired interrupt frequency) ] - 1
42

Mode timer Atmel


43

Timer 0
Registers
44

Timer 1
Registers
45

Timer 2
Registers
46

Setting bit
TCCR0A
TCCR0B
47

Setting bit
TCCR1A
TCCR1B
48

Contoh Setting Timer - Lanjutan


49
50
51
52
53
54

• UAS BOLEH BAWA A4 HANYA BERISI


TABEL SETTING REGISTER TIMER

• TIDAK BOLEH ADA PENJELASAN SAMA


SEKALI

• TIDAK BOLEH BERISI RUMUS APA PUN

• CURANG  NILAI = E & AKAN


DILAPORKAN KE STEI/ITB UNTUK
DIPROSES LEBIH LANJUT

You might also like