Programmable Interval Timer: Difference between revisions
[unchecked revision] | [unchecked revision] |
Content deleted Content added
→See Also: Add Wikipedia external link. |
m Bot: Replace deprecated source tag with syntaxhighlight |
||
(34 intermediate revisions by 25 users not shown) | |||
Line 1:
The '''Programmable Interval Timer''' ('''PIT''') chip (
== The Oscillator ==
The oscillator used by the PIT chip runs at (roughly) 1.193182 MHz. The reason for this requires a trip back into history (to the later half of the 1970's)...
The original PC used a single "base oscillator" to generate a frequency of 14.31818 MHz because this frequency was commonly used in television circuitry at the time. This base frequency was divided by 3 to give a frequency of 4.77272666 MHz that was used by the CPU, and divided by 4 to give a frequency of 3.579545 MHz that was used by the CGA video controller. By logically ANDing these signals together a frequency equivalent to the base frequency divided by 12 was created. This frequency is 1.1931816666 MHz (where the 6666 part is recurring). At the time it was a brilliant method of reducing costs, as the 14.31818 MHz oscillator was cheap due to mass production and it was cheaper to derive the other frequencies from this than to have several oscillators. In modern computers, where the cost of electronics is much less, and the CPU and video run at much higher frequencies the PIT lives on as a reminder of "the good ole' days".
== Frequency Dividers ==
The basic principle of a frequency divider is to divide one frequency to obtain a slower frequency. This is typically done by using a counter. Each "pulse" from the input frequency causes the counter to be decreased, and when that counter has reached zero a pulse is generated on the output and the counter is reset. For example, if the input signal is 200 Hz and the counter is reset to a value of ten each time, then the output frequency would be 200/10, or 20 Hz.
The PIT has only 16 bits that are used as frequency divider, which can represent the values from 0 to 65535. Since the frequency can't be divided by 0 in a sane way, many implementations use 0 to represent the value 65536 (or 10000 when programmed in BCD mode).
The PIT chip has three separate frequency dividers (or 3 separate channels) that are programmable, in that the
Each PIT channel also has a "gate input" pin which can be used to control whether the input signal (the 1.19MHz one) gets to the channel or not. For
== PIT Timer Accuracy ==
The accuracy of the PIT timer depends on the quality of the oscillator used, and is typically accurate to within +/- 1.73 seconds per day. There are many causes for this inaccuracy, however because of this there isn't much point in specifying times or frequencies to more than five or six digits.
== Outputs ==
Channel 0 is connected directly to IRQ0, so it is best to use it only for purposes that should generate interrupts. Channel 1 is unusable, and may not even exist. Channel 2 is connected to the PC speaker, but can be used for other purposes without producing audible speaker tones.
=== Channel 0 ===
The output from PIT channel 0 is connected to the PIC chip, so that it generates an "IRQ 0". Typically during boot the BIOS sets channel 0 with a count of 65535 or 0 (which translates to 65536), which gives an output frequency of 18.2065 Hz (or an IRQ every 54.9254 ms). Channel 0 is probably the most useful PIT channel, as it is the only channel that is connected to an IRQ. It can be used to generate an infinte series of "timer ticks" at a frequency of your choice (as long as it is higher than 18 Hz), or to generate single CPU interrupts (in "one shot" mode) after programmable short delays (less than an 18th of a second).
When choosing [[#Operating Modes|an operating mode]], below, it is useful to remember that the IRQ0 is generated by the ''rising edge'' of the Channel 0 output voltage (ie. the transition from "low" to "high", only).
=== Channel 1 ===
The output for PIT channel 1 was once used (in conjunction with the DMA controller's channel 0) for refreshing the DRAM (Dynamic Random Access Memory) or RAM. Typically, each bit in RAM consists of a capacitor which holds a tiny charge representing the state of that bit, however (due to leakage) these capacitors need to be "refreshed" periodically so that they don't forget their state.
On
=== Channel 2 ===
The output of PIT channel 2 is connected to the PC speaker, so the frequency of the output determines the frequency of the sound produced by the speaker. This is the only channel where the gate input can be controlled by software (via bit 0 of I/O port 0x61), and the only channel where its output (a high or low voltage) can be read by software (via bit 5 of I/O port 0x61). Details of how to program the PC speaker can be found [[PC_Speaker|here]].
== I/O Ports ==
The PIT chip uses the following I/O ports:
Line 55 ⟶ 48:
Bits Usage
The "Select Channel" bits select which channel is being configured, and must always be valid on every write of the mode/command register, regardless of the other bits or the type of operation being performed. The "read back" (both bits set) is not supported on the old 8253 chips but should be supported on all AT and later computers except for PS/2 (i.e. anything that isn't obsolete will support it). The "read back" command is discussed later.
The "Access Mode" bits tell the PIT what access mode you wish to use for the selected channel, and also specify [[#Counter Latch Command|the "counter latch" command]] to the CTC
The "Operating Mode" bits specify which mode the selected PIT channel should operate in. For the "read back" command and the "counter latch" command, these bits have different meanings (see the information corresponding to these commands below). There are 6 different [[#Operating Modes|operating modes]]. Each operating mode will be discussed separately later.
The "BCD/Binary" bit determines if the PIT channel will operate in binary mode or BCD mode (where each 4 bits of the counter represent a decimal digit, and the counter holds values from
== Operating Modes ==
While each operating mode behaves differently, some things are common to all operating modes. This includes:
; '''Initial Output State'''
: Every time the mode/command register is written to, all internal logic in the selected PIT channel is reset, and the output immediately goes to
; '''Changing Reload Value'''
: A new reload value can be written to a PIT channel's data port at any time. The operating mode determines the exact effect that this will have.
; '''Current Counter'''
: The current counter value is always either decremented or reset to the reload value on the ''falling'' edge of the (1.193182 MHz) input signal.
; '''Current Counter Reload'''
: In modes where the current count is decremented when it is reloaded, the current count is not decremented on the same input clock pulse as the reload
=== Mode 0
For this mode, when the mode/command register is written the output signal goes low and the PIT waits for the reload register to be set by software, to begin the countdown. After the reload register has been set, the current count will be set to the reload value on the next falling edge of the (1.193182 MHz) input signal. Subsequent falling edges of the input signal will decrement the current count (if the gate input is high on the preceding rising edge of the input signal).
Note: despite the misleading name of this mode, it only generates interrupts on channel 0.
=== Mode 1 – Hardware Re-triggerable One-shot ===
This mode is similar to mode 0 above, however counting doesn't start until a rising edge of the gate input is detected. For this reason it is not usable for PIT channels 0 or 1 (where the gate input can't be changed).
When the mode/command register is written the output signal goes high and the PIT waits for the reload register to be set by software. After the reload register has been set the PIT will wait for the next rising edge of the gate input. Once this occurs, the output signal will go low and the current count will be set to the reload value on the next falling edge of the (1.193182 MHz) input signal. Subsequent falling edges of the input signal will decrement the current count.
When the current count decrements from one to zero, the output goes high and remains high until another mode/command register is written or the reload register is set again. The current count will wrap around to 0xFFFF (or 0x9999 in BCD mode) and continue to decrement until the mode/command register or the reload register are set, however this will not
If the gate input signal goes low during this process it will have no effect. However, if the gate input goes high again it will cause the current count to be reloaded from the reload register on the next falling edge of the input signal, and restart the count again (the same as when counting first started).
The reload value can be changed at any time, however the new value will not
=== Mode 2 – Rate Generator ===
This mode operates as a frequency divider.
Line 127 ⟶ 118:
If the gate input goes low, counting stops and the output goes high immediately. Once the gate input has returned high, the next falling edge on input signal will cause the current count to be set to the reload value and operation will continue.
The reload value can be changed at any time, however the new value will not
A reload value (or divisor) of one must ''not'' be used with this mode.
This mode creates a high output signal that drops low for one input signal cycle (0.8381 uS), which is too fast to make a difference to the PC speaker (see mode 3). For this reason mode 2 is useless for
Typically, OSes and BIOSes use mode 3 (see below) for PIT channel 0 to generate IRQ 0 timer ticks, but some use mode 2 instead, to gain frequency accuracy (frequency = 1193182 / reload_value Hz).
=== Mode 3 – Square Wave Generator ===
For mode 3, the PIT channel operates as a frequency divider like mode 2, however the output signal is fed into an internal "flip flop" to produce a square wave (rather than a short pulse). The flip flop changes its output state each time its input state (or the output of the PIT channel's frequency divider) changes. This causes the actual output to change state half as often, so to compensate for this the current count is decremented twice on each falling edge of the input signal (instead of once), and the current count is set to the reload value twice as often.
When the mode/command register is written the output signal goes high and the PIT waits for the reload register to be set by software. After the reload register has been set, the current count will be set to the reload value on the next falling edge of the (1.193182 MHz) input signal. Subsequent falling edges of the input signal will decrement the current count twice (if the gate input is high on the preceding rising edge of the input signal).
Note: under normal circumstances the output state will be low 50% of the time when the mode/command register is written. The output will then go high, which will generate an immediate (perhaps spurious) IRQ0. The other 50% of the time the output will already be high, and there will be no IRQ0 generated.
For even reload values, when the current count decrements from two to zero the output of the flop-flop changes state; the current count will be reset to the reload value and counting will continue.
For odd reload values, the current count is always set to one less than the reload value.
If the output of the flip flop is low when the current count decrements from two to zero it will behave the same as the equivalent even reload value. However, if the output of the flip flop is high the reload will be delayed for one input signal cycle (0.8381 uS), which causes the "high" pulse to be slightly longer and the duty cycle will not be exactly 50%. Because the reload value is rounded down to the nearest even number anyway,
Note: This even value limitation on the reload value in mode 3 reduces the number of possible output frequencies in half. If you want to be able to control the frequency of IRQ0 to a somewhat higher degree, then think about using mode 2 instead for channel 0.
The reload value can be changed at any time, however the new value will not affect the current count until the current count is reloaded (when it is decreased from two to zero, or the gate input going low then high). When this occurs counting will continue using the new reload value.
A reload value (or divisor) of one must ''not'' be used with this mode.
=== Mode 4
Mode four operates as a retriggerable delay, and generates a pulse when the current count reaches zero.
When the mode/command register is written the output signal goes high and the PIT waits for the reload register to be set by software. After the reload register has been set, the current count will be set to the reload value on the next falling edge of the (1.193182 MHz) input signal. Subsequent falling edges of the input signal will decrement the current count (if the gate input is high on the preceding rising edge of the input signal).
When the current count decrements from one to zero, the output goes low for one cycle of the input signal (0.8381 uS). The current count will wrap around to 0xFFFF (or 0x9999 in BCD mode) and continue to decrement until the mode/command register or the reload register are set, however this will not
If the gate input goes low, counting stops but the output will not be
The reload value can be changed at any time. When the new value has been set (both bytes for "lobyte/hibyte" access mode) it will be loaded into the current count on the next falling edge of the (1.193182 MHz) input signal, and counting will continue using the new reload value.
=== Mode 5
Mode 5 is similar to mode 4, except that it waits for the rising edge of the gate input to trigger (or re-trigger) the delay period (like mode 1). For this reason it is not usable for PIT channels 0 or 1 (where the gate input can't be changed).
When the mode/command register is written the output signal goes high and the PIT waits for the reload register to be set by software. After the reload register has been set the PIT will wait for the next rising edge of the gate input. Once this occurs, the current count will be set to the reload value on the next falling edge of the (1.193182 MHz) input signal. Subsequent falling edges of the input signal will decrement the current count.
When the current count decrements from one to zero, the output goes low for one cycle of the input signal (0.8381 uS). The current count will wrap around to 0xFFFF (or 0x9999 in BCD mode) and continue to decrement until the mode/command register or the reload register are set, however this will not
If the gate input signal goes low during this process it will have no effect. However, if the gate input goes high again it will cause the current count to be reloaded from the reload register on the next falling edge of the input signal, and restart the count again (the same as when counting first started).
The reload value can be changed at any time, however the new value will not
== Counter Latch Command ==
To prevent the current count from being updated, it is possible to "latch" a PIT channel using the latch command. To do this, send the value CC000000 (in binary) to the mode/command register (I/O port 0x43), where 'CC' corresponds to the channel number. When the latch command has been sent, the current count is copied into an internal "latch register" which can then be read via the data port corresponding to the selected channel (I/O ports 0x40 to 0x42). The value kept in the latch register remains the same until it has been fully read, or until a new mode/command register is written.
The main benefit of the latch command is that it allows both bytes of the current count to be read without inconsistencies. For example, if you didn't use the latch command, then the current count may decrease from 0x0200 to 0x01FF after you've read the low byte but before you've read the high byte, so that your software thinks the counter was 0x0100 instead of 0x0200 (or 0x01FF).
== Read Back Command ==
The read back command is a special command sent to the mode/command register (I/O port 0x43). The "read back" is not supported on the old 8253 chips but should be supported on all AT and later computers except for PS/2 (i.e. anything that isn't obsolete will support it).
Line 189 ⟶ 181:
Bits Usage
Note: Be careful with bits 4 and 5
Bits 1 to 3 of the read back command select which PIT channels are
If bit 5 is clear, then any/all PIT channels selected with bits 1 to 3 will have their current count copied into their latch register (similar to sending the latch command, except it works for multiple channels with one command).
Line 210 ⟶ 202:
Bit/s Usage
The bottom six bits return the values that where programmed into the mode/command register when the channel was last initialized.
Line 235 ⟶ 227:
== Reading The Current Count ==
To read the current count using the "lobyte only" or "hibyte only" access modes, you can just do an "in al,0x40" (for PIT channel 0) without problems. For frequencies higher than 4.7 KHz it can be easiest to set the high byte of the reload value to zero, and then use the "lobyte only" access mode to minimize hassles.
For the "lobyte/hibyte" access mode you need to send the latch command (described above) to avoid getting wrong results. If any other code could try set the PIT channel's reload value or read its current count after you've sent the latch command but before you've read the highest 8 bits, then you have to prevent it. Disabling interrupts works for single CPU computers. For example, to read the count of PIT channel 0 you could use something like:
<syntaxhighlight lang="c">
unsigned read_pit_count(void) {
unsigned count = 0;
// Disable interrupts
cli();
// al = channel in bits 6 and 7, remaining bits clear
outb(0x43,0b0000000);
count = inb(0x40); // Low byte
count |= inb(0x40)<<8; // High byte
return count;
}
</syntaxhighlight>
== Setting The Reload Value ==
To set the reload value, just send the value/s to the corresponding data port. For the "lobyte only" or "hibyte only" access modes this only takes a single "out 0x40,al" (for PIT channel 0).
For the "lobyte/hibyte" access mode you need to send the low 8 bits followed by the high 8 bits. You must prevent other code from setting the PIT channel's reload value or reading its current count once you've sent the lowest 8 bits. Disabling interrupts works for single CPU computers. For example:
<syntaxhighlight lang="c">
void set_pit_count(unsigned count) {
// Disable interrupts
cli();
// Set low byte
outb(0x40,count&0xFF); // Low byte
outb(0x40,(count&0xFF00)>>8); // High byte
return;
}
</syntaxhighlight>
It should be noted that a reload value of zero can be used to specify a divisor of 65536. This is how the BIOS gets an IRQ 0 frequency as low as 18.2065 Hz.
== PIT Channel 0 Example Code ==
The following example code was written for NASM, but hasn't been tested.
The idea is to provide a single routine to initialize PIT channel 0 for any (possible) frequency and use IRQ 0 to accurately keep track of real time in milliseconds since the PIT was configured.
For the sake of accuracy, the initialization code will calculate the number of whole milliseconds to add to the "system timer tick" each IRQ, and the number of "fractions of a millisecond" to avoid drift. This may be important, for example if the PIT is set for 700 Hz it'd work out to (roughly) 1.42857
To begin with, this following code contains all of the data used by this example. It is assumed that the ".bss" section is filled with zeros.
<syntaxhighlight lang="asm">
section .bss
PIT_reload_value: resw 1 ; Current PIT reload value
section .text
</syntaxhighlight>
Next is the handler for IRQ 0. It's fairly simple (all it does it add 2 64 bit fixed point values and send an EOI to the PIC chip).
<syntaxhighlight lang="asm">
IRQ0_handler:
push ebx
</syntaxhighlight>
Now for the tricky bit
For some extra accuracy, I also use "3579545 / 3" instead of 1193182 Hz. This is mostly pointless due to inaccurate hardware (I just like being correct).
<syntaxhighlight lang="asm">
;Input
; ebx Desired PIT frequency in Hz
Line 376:
; Note: The basic formula is:
; time in ms = reload_value / (3579545 / 3) * 1000
; This can be rearranged in the
; time in ms = reload_value * 3000 / 3579545
; time in ms = reload_value * 3000 / 3579545 * (2^42)/(2^42)
Line 389:
shr edx,10 ;edx:eax = reload_value * 3000 * (2^42) / 3579545 / (2^10)
mov [
mov [IRQ0_fractions],eax ;Set fractions of 1
Line 410:
popad
ret
</syntaxhighlight>
Of course it's easier to configure the PIT to a fixed value, but where's the fun in that? :-)
Line 417 ⟶ 418:
==Uses for the Timer IRQ==
===Using the IRQ to Implement <tt>sleep</tt>===
The PIT's generating a hardware interrupt every ''n'' milliseconds allows you to create a simple timer. Start with a global variable
<syntaxhighlight lang="C">
volatile uint32_t CountDown;
</syntaxhighlight>
Next, every time the timer interrupt is called, decrement this variable until 0 is stored.
<syntaxhighlight lang="asm">
section .text
global TimerIRQ
TimerIRQ:
test eax, eax
mov [CountDown], eax
TimerDone:
</syntaxhighlight>
Finally, create a function <tt>sleep</tt> that waits the interval, in milliseconds.
<syntaxhighlight lang="c">
void sleep(uint32_t millis) {
CountDown
while
halt();
}
}
</syntaxhighlight>
In a multitasking system, consider using a linked list or array of these CountDown variables. If your multitasking system supports interprocess communication, you can also store the semaphore/exchange where two processes can talk to, have the interrupt send a message to the waiting process when the timer is done, and have the waiting process block all execution until that message comes:
<syntaxhighlight lang="c">
#define COUNTDOWN_DONE_MSG 1
struct TimerBlock {
EXCHANGE e;
uint32_t CountDown;
} timerblocks[20];
void TimerIRQ(void) /* called from Assembly */
{
uint8_t i;
for (i = 0; i < 20;
if (timerblocks[i].CountDown == 0)
SendMessage(timerblocks[i].e, COUNTDOWN_DONE_MESSAGE);
}
}
void Sleep(uint32_t delay)
{
struct TimerBlock *t;
if ((t = findTimerBlock()) == nil)
return;
t->CountDown = delay;
WaitForMessageFrom(t->e = getCrntExch());
}
</syntaxhighlight>
In your documentation, note the interval of the timer. For example, if the timer interval is 10 milliseconds per tick, tell the programmer to issue
<syntaxhighlight lang="c">
Sleep(100);
</syntaxhighlight>
to sleep for a single second.
Line 498 ⟶ 493:
=== Articles ===
* [[Time And Date]]
* [[RTC]]
=== Threads ===
=== External Links ===
*[[wikipedia:Programmable Interval Timer | Programmable Interval Timer]] on Wikipedia
*[http://www.osdever.net/bkerndev/Docs/pit.htm The PIT: A System Clock] on osdever
[[Category:Common Devices]]
[[Category:Timers]]
[[de:Programmable_Interval_Timer]]
|