Freescale Semiconductor Application Note AN2897 Rev. 0, 11/2004 Using the eTPU Angle Clock by: Mike Pauwels TECD Systems Applications Engineering This document describes the Angle Clock feature of the Enhanced Time Processor Unit and offers practical advise on the application and use of this feature. The note assumes a familiarity with the eTPU and the eTPU_C language used in the Byte Craft compiler. Code examples presented below are taken from a Reference design which is available from your Freescale representative. 1 Overview The Enhanced Time Processor Unit (eTPU) is an autonomous slave processor offered on various families of Freescale microcontrollers. The processor is tightly coupled to up to 32 channels, each associated with an input and an output signal. The input/output channels each have a pair of Match and Capture units interfaced to one of two timer/counter (TCR) registers. Logic in the channel enabled the hardware to detect or drive pin transitions with a high degree of timing precision. In a typical application, at least one of the TCRs is driven by a real time clock derived from the MCU clock frequency. The second TCR can be driven by an © Freescale Semiconductor, Inc., 2004. All rights reserved. Table of Contents 1 2 2.1 2.2 2.3 2.4 2.5 3 3.1 3.2 3.3 3.4 3.5 4 4.1 4.2 5 5.1 5.2 5.3 6 Overview .............................................................1 eTPU Angle Clock Hardware.............................3 Tooth Wheel Input..............................................5 Tick Counter ......................................................5 Missing Teeth.....................................................6 Zero Count Synchronization ..............................7 Error Recovery ....................................................7 System Design ....................................................8 Steady State System Design.............................9 Acceleration and Deceleration.........................11 Startup System Design....................................13 Anomalies........................................................15 Tooth Circuit Failure.........................................18 eTPU Software Design ....................................18 Host Setup.......................................................18 State Machine Description...............................19 Angle Clock Application ...................................27 Free Running Angle Counter ...........................27 Periodic Angle Clock........................................28 Angle Math ......................................................28 Summary ...........................................................29 Overview asynchronous external signal, by a real time clock with a different time base, or by special Angle Clock circuitry on the eTPU. The purpose of the Angle Clock is to synchronize with the angle of a spinning shaft and provide a counter representation of the instantaneous position of the shaft. If the shaft provides an input signal related to teeth spaced along the circumference, the Angle Clock extrapolates the number of ticks between the adjacent pairs of teeth, thereby providing a finer resolution of angle than the shaft signal alone can provide. The Angle Clock was designed for automotive engine control, but finds application in a variety of rotational devices. An Angle Clock can be implemented in hardware or in software, but either implementation has limitations. A software angle clock cannot divide an input tooth signal into very fine ticks without overwhelming the processor. Even before the tick rate reaches its limit, latency on the processor will begin to distort the ideal count pattern. A hardware angle clock can provide very fine resolution of the ticks, but the hardware becomes complex and large when the logic is required to handle errors and exceptional input signals. The eTPU Angle Clock has been implemented as a software supported hardware subsystem, effectively eliminating both of these significant limitations. The hardware subsystem has provisions for fast tick counting plus compensation for missing teeth, which are often used to provide an angle key for the shaft. The hardware also provides automatic compensation for acceleration and deceleration, and assists in error recovery. The software handles synchronization and exception handling. Sensor Toothed Wheel ‘36 - 1’ 35 Teeth Spaced 10º Figure 1. Toothed Wheel Using the eTPU Angle Clock, Rev. 0 2 Freescale Semiconductor eTPU Angle Clock Hardware 2 eTPU Angle Clock Hardware The eTPU Angle Clock provides a counter that can be synchronized to a periodic input signal such as would be produced by a sensor detecting teeth on a wheel attached to a rotating shaft. A typical toothed wheel used in automotive applications might have 35 teeth spaced at 10 degree intervals with a missing tooth in the 36th position (Figure 1). The Angle Clock hardware detects and times the teeth, compensates for the missing teeth, and inserts a fixed number of additional counts (ticks) between each pair of teeth at a rate determined by eTPU software. Typically, a system would insert 100 counts between each pair of teeth, giving an angle resolution of 0.1 degree. The Angle Clock is maintained in TCR2, one of two selectable timer counter registers in the eTPU, which can be used by any channel to cause pin action and/or service requests on a match, or which can be captured as a result of an input pin action. In addition, the eTPU can export the angle clock to another eTPU or to an eMIOS device connected to a common Shared Timer and Counter (STAC) bus. The angle clock can be read in real time by the host. The eTPU Angle Clock operates as a state machine, processing inputs from the input pin and using parameters provided by the eTPU software. A simplified diagram of the eTPU Angle Clock logic is shown in Figure 2. Tooth Edge Hold Miss Count dec MISSCNT wait TRR time tickctr = TICKS MISSCNT > 0 tickctr = TICKS MISSCNT = 0 New Edge if LAST then TCR2 = 0 else incr TCR2 tickctr = 0 New Tooth incr TCR2 tickctr = 0 Tick Time wait TRR time TRR time-out tickctr > TICKS Tooth Edge tickctr ≤ TICKS Tick Count inc tickctr; incr TCR2 Fast Count inc tickctr; incr TCR2 wait clock/8 tickctr ≤ TICKS Figure 2. Angle Clock Simplified State Diagram The heart of the Angle Clock is a tick generator that inserts a selected number of ticks between each pair of teeth. A block diagram of the tick generator is shown in Figure 3. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 3 eTPU Angle Clock Hardware Filtered Pin Level To Channel 0 Edge Detection (override its digital filter) Programmable Window from Channel 0 in Angle Mode TDL assertion on channel 0 TCR2 Filtering Count Clock System & Edge Detect TCRCLK PIN TCR2 Clock Microengine A-Bus 24 24 Angle Tick Generator Tick Rate Register Integer Fraction 24 15 9 9 Carry 9 TCR1 Clock Din + Hold Fraction Accumulator Load Tick Prescaler H.Rate 9 AM (ETPUTBCR) Angle Mode Angle Tick TCR2 Tooth Tooth: Advance, Reset 10 2 Angle Tick Inc/Hold Angle Tick Reset 24 Ticks Tooth Program Register 10 2 Dummy Tooth Count Angle Tick Count Count Contol & High Rate Logic 10 Last Tooth Angle Mode AM (ETPUTBCR) TCR2 Time Base Angle Counter Logic . Figure 3. eTPU Angle Clock Tick Generator Using the eTPU Angle Clock, Rev. 0 4 Freescale Semiconductor eTPU Angle Clock Hardware 2.1 Tooth Wheel Input When an eTPU is placed into Angle Clock mode by programming the AM bit in the register ETPUTBCR, the input to Channel 0 of the device is connected internally to the external clock input TCRCLK. This input has an independently programmed hardware filter circuit which enables the user to select a different input filter treatment from the rest of the eTPU input pins if desired. The filtered input signal is applied to the Angle Clock hardware circuitry. This hardware is part of channel 0 input and the signal to the angle clock can be conditioned by matches according to the selected mode for the channel. For example, the channel can be placed in m2_st (Match2SingleTransition) mode, and the eTPU software can establish a window for accepting a tooth signal from the wheel. A signal arriving too early might indicate noise and could be ignored, while one arriving too late could indicate a stall and might require special exception processing. 2.2 Tick Counter When the Angle Clock is running on channel 0 of an eTPU, an input signal detected by the channel increments TCR2. When this count occurs, a tick counter is started in the Angle Clock circuitry. This counter increments TCR2 at a rate set by the value in the Tick Rate Register (TRR), which is programmed in terms of TCR1 cycles. Thus if the TRR were written with a value of 100, and the TCR1 count rate was set at 0.1 microsecond, the TCR2 counter would increment once every 10 microseconds. The TRR is written by eTPU software from a value derived from the projected speed of the wheel. If the application requires 200 ticks per tooth, the eTPU software will typically measure the period of the last tooth pair in terms of TCR1, and divide the value by 200 to get the TRR value. The TRR can be programmed with a whole number and fraction of a count. As the count proceeds, the Angle Clock logic accumulates the fraction, and adjusts the count to compensate for the fraction. The software also programs the number of inserted counts into the field TICKS in the Tooth Program Register (TPR). If there are 100 ticks per tooth period, then TICKS would be programmed with 99. The tick counter is designed to count exactly TICKS+1 periods between detected physical teeth. Under constant speed operation, TICKS +1 times the TRR rate will be exactly equal to the period between the teeth. When the following tooth signal arrives late, the Angle Clock stops after incrementing the TCR2 by TICKS counts. Thus the Angle Clock is said to be in Halt mode while the slowing wheel catches up with the Angle Clock count. When the next tooth arrives, it is counted in TCR2 and the Angle Clock reverts to Normal mode with tick counts added for the following tooth period. Thus the Angle clock cannot proceed to the next tooth count until the physical tooth is detected. If the wheel is accelerating, the tooth signal may be detected before the TICKS count has completed. In this event, the Angle Clock hardware is put into a High Rate count mode. The tick count completes at an accelerated rate equal to 1/8 of the MCU system clock (regardless of the TCR1 rate). This allows the Angle Clock to catch up with the physical teeth. After the last tick is counted, the Angle Clock will count the newly arrived tooth at the same rate. The high rate has been chosen to ensure that any eTPU or external action triggered by a specific value of the angle clock can be detected and acted upon. NOTE The Angle Clock is designed to count all TICKS between teeth, never skipping a count, and never proceeding with a count for the new tooth until the physical tooth is detected. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 5 eTPU Angle Clock Hardware 2.3 Missing Teeth Typically a toothed wheel used in automotive applications has a series of equally spaced teeth with one or more teeth removed to provide a reference point. The Angle Clock hardware has circuitry to insert the tooth count for these missing teeth under control of eTPU software. One to three missing teeth can be added automatically by programming the field MISSCNT to a non-zero value after the last tooth edge before the gap. When the eTPU software programs MISSCNT to a non-zero value, the tick counter proceeds as normal until the last count of the TICKS value is reached. Then after an additional TRR period, MISSCNT is tested, and when it is found to be non-zero, it is decremented and TCR is incremented as if a physical tooth had been detected. The TCR continues to increment at TRR rate according to the TICKS value for the period after the missing tooth. This process is repeated for all missing teeth. See Figure 4 Detected tooth edge Inserted Teeth Angle Clock (TCR2) resets to 0 Tick bursts MISSCNT decrements to 0 MISSCNT decrements to 1 Software write MISSCNT = 2, sets LAST Figure 4. Missing Teeth The Angle Clock remains in Normal mode throughout the missing tooth count unless a new physical tooth is detected before the final tick is counted. In that event the Angle Clock goes into High Rate mode and completes the accelerated cycle as described above. Using the eTPU Angle Clock, Rev. 0 6 Freescale Semiconductor eTPU Angle Clock Hardware If the Angle Clock completes the count of the missing teeth plus all of the inserted ticks, and a new tooth is not detected, the Angle Clock goes into Halt mode as described above. 2.4 Zero Count Synchronization For continuous synchronization of the Angle Clock with the position of the wheel, the Angle Clock has a feature to zero the TCR2 count on detection of a software designated edge. To use the automatic synchronization feature of the Angle Clock, the zero count must coincide with a physical tooth edge. After the last tooth before the zero count synchronization, the software sets the LAST bit in the TPR to indicate that the current tooth is the last one in the count cycle. Then, when the next tooth is detected, the TCR2 count will automatically reset to 0 if the Angle Clock is in the Normal or Halt mode. If the Angle Clock is in the High Rate mode when a tooth is detected with the LAST bit set, the Angle Clock will continue the count of the ticks until it is complete before resetting the TCR2. When TCR2 is reset by a tooth edge with LAST set, the action also clears the LAST bit. When the application uses the zero count synchronization feature to reset the TCR2 counter on a designated tooth each revolution, the TCR2 counter will continuously maintain a value proportional to the angle of the wheel over a 360 degree range. At steady state, if the software is properly implemented, the ticks between the teeth will be accurate within about one TCR1 count. Under deceleration, the tick positions may be in error, but the tooth angles will be accurate, while under acceleration, the tooth positions may be delayed while the tick count catches up at a high count rate. If the software sets the LAST bit on alternate revolutions of the wheel, the TCR2 counter will count over an angle range of 720 degrees before resetting to zero. This is an important feature for 4-cycle automotive applications, where the control cycle is 720 degrees. 2.5 Error Recovery The eTPU Angle Clock hardware provides no automatic means to detect errors in the tooth count while tracking the wheel angle. If missing teeth are programmed between two normally spaced teeth, the hardware will absolutely insert the required counts, likely going into High Rate mode for a significant portion of the count. If no missing teeth are inserted in a gap, the counter will count no higher than TICKS counts and then go into Halt mode for the rest of the gap. If LAST is asserted on the wrong tooth, the TCR2 counter will reset, regardless of the TCR2 count, when the next tooth is detected. If the Angle Clock is untracked by missed detection of a tooth or spurious additional tooth, it is incumbent on the software, either in the host or the eTPU, to detect the error and initiate corrective action. The Angle Clock hardware does provide means to make a correction in the TCR2 count when an error is verified by the software. If the application determines that the Angle Clock has missed a tooth count and is running with a one tooth deficit in the count, the eTPU software can insert an additional tooth by asserting the IPH bit in the TPR. When this signal is asserted, the hardware reacts exactly as if a physical tooth was detected. If the tick counter is counting in Normal mode, it switches to High Rate mode, completes the current tick count, then counts the inserted tooth and continues in Normal mode. If the Angle Clock is in Halt mode, it counts the inserted tooth and starts a tick count in Normal mode. Note that if the IPH is asserted in High Rate mode, it is ignored. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 7 System Design NOTE Inserting a tooth by asserting IPH will increase the TCR2 count by exactly one tooth angle by counting forward to the new angle. No counts are skipped. If the application determines that the Angle Clock is ahead of the wheel, it can slow the count by asserting the HOLD bit in the TPR. When this signal is asserted, the Angle Clock hardware immediately suspends the count until an new tooth is detected. When the new tooth is detected, the Angle Clock operation resumes from the count it held when the HOLD bit was set. NOTE Asserting HOLD stops the TCR2 count for exactly one tooth angle. There are certain restrictions and limitations to the use of the various signals in the Angle Clock TPR register. • IPH may be used to reset the counter, if LAST is asserted when IPH is set. • MISSCNT can be used to insert more than three missing teeth with the restriction that if MISSCNT is to be written on the same tooth as the LAST bit is set, the two fields must be written together. • Do not use IPH to cancel a HOLD that is in progress. Simply clear the HOLD bit. • When the tick counter is in High Rate mode only IPH and HOLD can have immediate effect. All other fields in the TPR are buffered until the Angle Clock exits High Rate mode. • If the TICKS field is changed before the Angle Clock goes into Halt mode, the tick counter will attempt to use the new value immediately after the current tick occurs. Note that the Angle Clock does not go into Halt mode until approximately one TRR time after the last tick is counted. Please refer to the Reference Manual for details. 3 System Design There are four operating conditions that must be considered in the system design process: steady state operation, acceleration and deceleration, startup, and exception handling. The first two conditions covers a large majority of the operating time of the system but requires only a small portion of the development time. Startup is more complex, while exception processing tries to anticipate large numbers of exceedingly rare error conditions, which must be handled competently without human intervention. Since the eTPU is only a small slave processor associated with a powerful MCU central processor, the system approach should be to entrust the steady state operation an much as possible to the eTPU, with assistance in startup. The eTPU might help in error detection, but since the exception handling may be complex, the proper systems approach is to use the eTPU to detect anomalies, but correct the errors where possible in the CPU. Using the eTPU Angle Clock, Rev. 0 8 Freescale Semiconductor System Design 3.1 Steady State System Design There are two basic angle counting modes that can be supported by the eTPU. In the periodic mode, the TCR2 can be programmed to maintain a real time representation of the absolute angle of the wheel with respect to a reference position, while in the free running mode it can track a continuously increasing angle from startup, rolling over as the TCR1 (time) counter does after reaching 0XFFFFFF (16777215) counts. The choice between these modes depends on the desired mode of comparison of angle positions. 3.1.1 Periodic Angle Clock If the Angle Clock software sets LAST at the end of a cycle, typically at 360 or 720 degrees, the TCR2 counter will roll over to 0 at the tooth edge after LAST. This means that comparison to the engine angle must be done as equals-only. The greater-or-equal compare depends on the count rolling over after 0XFFFFFF. Greater-or-equal compares will be satisfied for any number from 0 to 0X7FFFFF less than the programmed angle. This means that an attempt to setup a compare in the future will not work properly if the future projected angle rolls over the end angle. In other words, 0 degrees will always test less than any other angle, including 715 degrees, even though with the periodic Angle Clock, it is 5 degrees in the future. Engineers are understandably uneasy about using an equal-only compare. If a spark is programmed to fire at 32 degrees, missing the angle under any exceptional condition will cause an undesirable misfire. However, the eTPU Angle Clock is designed not to miss any comparison counts regardless of the speed dynamics of the input signal. This means that any compare that is programmed to occur at a selected angle will absolutely occur at the next occurrence of that angle in TCR2. The only danger is in writing the compare value just too late for the intended cycle. If the spark time was changed, for example, to 31 degrees just after the Angle Clock reached 31.1 degrees, the spark could be missed. Therefore it must be a requirement of all angle triggered driver software to test for any change that steps the compare point over the current angle, and force the compare immediately when that happens. 3.1.2 Free Running Angle Clock To avoid the step-over problem mentioned above, a designer might choose to use the greater-or-equal comparator in the eTPU channel with a free running Angle Clock. In this case, the trigger angle for any function must be offset by the angle at a reference point on the wheel. For example, the software driver could maintain the top dead center (TDC) value for the current cylinder. If the spark is set to 12 degrees before TDC, the driver need only subtract the 12 degrees from the TDC angle to get an absolute firing point. Regardless when the software is updated, the greater-or-equal compare will ensure that a event is not missed. Then at some point in the cycle, for each driver the TDC angle must be updated for the next cycle. The disadvantage of using a free running Angle Clock is that a host read of TCR2 will not directly yield the absolute position of the engine. The value will have to be reduced by a reference angle, modulus 360/720 degrees, and the reference angle will have to be updated every revolution. Either the periodic or the free running Angle Clock can be applied successfully to an engine control system. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 9 System Design 3.1.3 Angle Resolution The eTPU Angle Clock can resolve the angle between the teeth into as many as 1024 ticks. However the proper selection of the TICKS value in the TPR must take into account other considerations. To understand the limits for TICKS in a given system, the engineer must consider the configuration of the toothed wheel, the maximum and minimum speed that must be processed, and the selected resolution of the TCR1 counter. The TCR1 counter resolution is usually a compromise between the finest resolution required by the eTPU channel drivers and the maximum pulse width that must be measured or driven. In fact, arbitrarily long pulses can be processed regardless of the TCR1 resolution by using software intervention, so the maximum time is seldom a great consideration. The minimum TCR1 resolution is two times the period of the MCU system clock. However, many systems engineers choose a convenient value derived from the clock. A typical TCR1 resolution might be 100 nanoseconds. The would enable the eTPU to time out pulses up to about 0.8 seconds with a single write to a match register. (Using the greater-than-or-equal comparison, the future equals half the range of the counter. Values larger than 0x800000 above the TCR value are considered in the past, and will match immediately using the greater-than-or-equal comparison.) Now consider the TRR. It is organized as a 1-bit integer and a 9-bit fraction.This means that the largest value for a single tick would be 0X7FFF.1FF (32767.998) times the period of the TCR. Since a zero value in the integer field is processed as 32768, the minimum TRR value is actually 1. There are reasons to avoid both of these extremes, so the user should build in a little margin when setting the limits. The maximum number of ticks per tooth should ensure that there is more than one TCR1 time per tick at the maximum speed for the wheel. The minimum number of ticks per tooth should ensure that the maximum value of TRR is not exceeded at the minimum wheel speed. EXAMPLE Assume a TCR1 time of 100 nanoseconds, a maximum speed of 10,000 RPM and a 36 tooth (10 degree) wheel, 1 *MaxTicks < DegreesPerTooth * TRC1_Frequency / (60 * RPM_Maximum) MaxTicks < 1 * 10.0 * 10,000,000 / 60 * 10,000 = 166. ticks per tooth Assume a TCR1 time of 100 nanoseconds, a minimum speed of 20 RPM and a 36 tooth (10 degree) wheel, 32768 * MinTicks > DegreesPerTooth * TRC1_Frequency / (60 * RPM_Minimum) MinTicks > 10.0 * 10,000,000 / (60 * 20 * 32768) = 2.543 ticks per tooth choose 100 for 10 ticks per degree (0.1 degree per tick) 3.1.4 Reference Point The reference point for a periodic angle clock should be on a selected physical tooth edge. Typically this might be the first tooth edge after the gap, but any edge can be chosen. Note that if the Angle Clock is to cycle through 720 degrees rotation, the resetting tooth is found on alternate rotations of the wheel. Using the eTPU Angle Clock, Rev. 0 10 Freescale Semiconductor System Design Selecting an absolute reference for the 720 degree cycle must be done using an external reference such as a cam shaft sensor. The Angle Clock will automatically reset to zero if a physical tooth edge is detected with the LAST bit set in the TPR. This means that the system software must keep track of the tooth count and write the LAST bit at the appropriate time. 3.1.5 Missing Teeth In an automotive engine control system, the toothed wheel on the crankshaft typically has one or more missing teeth to provide an angular reference point. The Angle Clock hardware can provide compensation for these missing teeth, adding a tooth count and repeating the tick count for each missing tooth to bridge the gap in the teeth. The system software must keep track of the tooth count and, after the last edge before the gap, write the number of expected missing teeth to the MISSCNT field in the TPR. 3.1.6 Tick Rate The eTPU can automatically record the time of a tooth transition on the Channel 0 input. If the software has stored the previous edge time, then the period of the tooth signal can be calculated by subtracting the times. To derive the value for the TRR, the software must divide the time for a tooth period by the number of ticks per tooth. This calculation must be adjusted if the most recent period was measured over the gap. Note that the tooth period is a measure of the rotational speed of the engine. Typically this value is kept in a global memory location. In that case, it should be updated with the adjusted period when measured over the gap. 3.2 Acceleration and Deceleration Speed changes in the wheel can be easily handled by the eTPU Angle Clock hardware if it is properly managed by the eTPU software. Since the tick counter is an extrapolation of the speed of the wheel, the accuracy of the ticks is determined by the accuracy of the TRR value plus a possible error due to software latency. The systems engineer needs to understand the maximum acceleration expected in the wheel and design adequate compensation in the software. 3.2.1 Acceleration Acceleration is manifested in the Angle Clock by a tooth edge arriving earlier than expected whenever the period of the last tooth separation is less than the pervious period. When the previous tooth edge was detected, the TRR was written with a value that assumed evenly spaced ticks between that tooth and the next. Acceleration of the wheel means that the latest tooth is detected before the tick count is completed. When this occurs, the Angle Clock switches automatically into High Rate mode. The balance of the ticks are counted at a rate equal to the MCU system clock (not TCR1) divided by eight. Once the tick count is complete, one additional count is added for the newly arrived tooth. The Angle Clock then reverts to the Normal mode. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 11 System Design Typically, the detection of the tooth edge causes the Channel 0 logic to request service from the eTPU engine. This service request is granted by a scheduler in a manner determined by the following: 1. If the eTPU is idle and no other channel is requesting service, the scheduler will grant the Channel 0 request immediately. The eTPU will require 6 system clocks to start executing the service thread. 2. If more than one channel is requesting service, the scheduler will arbitrate the requests according to the priorities and recent history of the scheduler. See the Reference Manual for a detailed treatment of the scheduler process. 3. If another channel is being serviced, the eTPU will complete the thread being serviced, then revert to 2. Presumably, the service thread will determine the previous period and calculate a new TRR value. Then, at some point in the thread, the TRR will be written. However, depending on latency, the new tick stream may have started counting before the updated TRR was written. In that event, all ticks that have been timed during the latency period will presumable be slow and, after the TRR is corrected, the current period may run late as well.This effect is actually rather small in real automotive systems, except perhaps during the very first firing while cranking. EXAMPLE A 36-1 (35 ten-degree teeth with one missing tooth) tooth wheels is running at 720 RPM when the engine is accelerated at a rate of 5000 RPM per second. If the Angle Clock was inserting 100 ticks per tooth, and the latency for the tooth service was 10 microseconds, what is the tick distribution in the first two gaps after acceleration starts? (system clock = 100 MHz) Original TRR value: 720 RPM * 1/60 * 36 = 432 teeth per second => 2.315 msec/tooth => 23.15 µsec/tick Speed change over the first tooth: 5000 RPM/sec * 0.002315 sec = 11.6 RPM Second TRR value: (720 + 11.6) RPM * 1/60 * 36 = 439 teeth per second => 2.278 msec/tooth => 22.78 µsec/tick Second tick count: 2.278 msec/23.15 µsec = 98.4 ticks The edge arrives when the count is 98, therefore count 99 and 100 (tooth count) occur at 0.08 and 0.16 µsec after the tooth arrives. The largest tick error would be tick 98 which would occur about (100 - 98.4) 1.6 ticks (0.16 degrees) late. Speed change over the second tooth: 5000 RPM/sec * 0.002278 sec = 11.4 RPM Third TRR value: (731.6 + 11.4) RPM * 1/60 * 36 = 446 teeth per second => 2.243 msec/tooth => 22.43 µsec/tick Third tick count: 2.243 msec/22.78 µsec = 98.5 ticks ...which we must adjust for the high rate counts plus the error in the first tick position: (0.16 µsec + (22.78µsec - 22.43µsec))/ 22.43 µsec/tick = 0.02 ticks The edge arrives when the count is about 98.5, therefore count 99 and 100 (tooth count) occur at 0.08 and 0.16 µsec after the tooth arrives. The largest tick error would be tick 98 which would occur about 1.5 tick positions (0.15 degrees) late. Using the eTPU Angle Clock, Rev. 0 12 Freescale Semiconductor System Design As can be seen from the example, the Angle Clock can track a typical automotive toothed wheel quite well under normal operating conditions. Also, the faster the speed, the less the effect of a given acceleration rate. 3.2.2 Deceleration When the Angle Clock completes the tick count and the next tooth does not arrive, it goes into Halt mode. Then when the next tooth does arrive it is counted and the tick count starts again with the previous low TRR value. When a new TRR value is calculated, the tick rate is decreased. The angle tracking under deceleration is similar to acceleration tracking. EXAMPLE In the example above, what is the error when the wheel decelerated from 731.6 RPM to 720 RPM in one tooth time? Second count theoretical minus second count actual: 99 * 23.15 µsec - 99 * 22.78 µsec = 36.6 µsec => 36.6 / 22.78 = 1.6 ticks The 99th tick arrives 36.6 µsec or 1.6 ticks early. This is the largest angle error (0.16 degrees). See also discussion of excessive acceleration and deceleration in Section 3.4, “Anomalies.” 3.3 Startup System Design Starting the Angle Clock requires three essential steps. First, the initial values must be written to the function parameters and control registers. Second, the tooth signal is acquired, the periods are tracked, and the tooth pattern is tested for a reference point, usually the first gap. Third, when the angle is determined, the actual angle is written to the TCR2, synchronizing it to the wheel and the rest of the angle based control system can be started. 3.3.1 Initial Parameter Values The Angle Clock hardware must be setup in the eTPU by writing certain control registers by the host. This includes writing the AM bit in the ETPUTBCR and configuring the TCRCLK input for the selected eTPU. If the Angle Clock is to be used as a server for another eTPU or for the eMIOS, the Shared Timing and Control (STAC) bus must be set up. The essential software steps will be detailed below. The Channel 0 parameters must be written to initial values by the host at startup. Most important are the Angle Clock hardware register values (which are subsequently written by the eTPU software to the registers) and the initial position of the Angle Clock. While the software is searching for the reference point, the Angle Clock may be held to a particular value, or it may be counting from some arbitrary point. The system designer should take care that other drivers in his system do not trigger on arbitrary value of TCR2 before the Angle Clock in synchronized. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 13 System Design There are several ways to avoid spurious matches and pin action during startup: • The eTPU may be kept out of Angle Mode until the channel hardware has searched and found the reference point. TCR2 can be disabled by writing 0b111 to the TCR2CTL field of the ETPUTBCR. NOTE Do not set TCR2CTL to 0b111 unless the Angle Mode is disabled by setting AM to 0. • • The Angle Clock can be allowed to run during startup, but other drivers dependent on the Angle Clock must be kept disabled until synchronization. While this strategy is used in the Reference Design, it is not the preferred strategy. TCR2 can be maintained at a large negative and/or out of range value during acquisition and synchronization. The main advantage of letting the Angle Clock run during startup and synchronization is to reduce the number of special cases handled in the software. 3.3.2 Acquisition and Synchronization The first detected tooth edge indicates that the wheel is moving. The only information that can be gathered is the TCR1 time of the edge. The second tooth provides a new edge time and the first tooth period. Note that in most systems the period value alone cannot distinguish between a normal tooth separation or the multiple tooth width of the gap. However, with the first period recorded, the system can now start to search for the first gap. Once the third tooth edge is detected, a second tooth period is known and the search for the gap can begin. There are various ways to identify the gap using the time between consecutive pairs of teeth. The larger the gap, that is the more teeth are missing, the easier it is to discriminate between normal teeth and the tooth gap. However, variations in period size can also indicate acceleration or deceleration of the wheel. If the size of tooth period is approximately twice the previous period, this might indicate a gap, or a severe deceleration of the wheel. A common way to ensure that a gap has been detected is to confirm the measurement on the following tooth edge. Whatever test is used to identify a long period can be applied in reverse to the following period to test for an ABA pattern of periods. The presumption here is that the wheel would not make a sudden sharp deceleration, followed one tooth later by a sudden sharp acceleration. Whether this or any other test is valid for a given system must be determined by the systems engineer. The ABA test is considered valid for automotive applications because of the significant inertia of the crankshaft. EXAMPLE Four consecutive tooth edge times are found to be: Capture[1] = 0x1B238A Capture[2] = 0x1CBA70 Capture[3] = 0x1FAB33 Capture[4] = 0x211145 Using the eTPU Angle Clock, Rev. 0 14 Freescale Semiconductor System Design Subtracting adjacent tooth times yields the following periods: Period[1] = 0x196E6 Period[2] = 0x2F0C3 Period[3] = 0x16612 We can use a “Gap Ratio” algorithm to test if this represents a gap detection. Use Gap_Ratio = 0.7 Is_Gap = if ((Period[2] * Gap_Ratio > Period[1]) && (Period[3] < Gap_Ratio * Period[2]) Period[2] * Gap_Ratio = 0x203BB This is larger than Period[1] and Period[3]... ...therefore the Is_Gap condition is satisfied. 3.3.3 Starting the Angle Clock Once the gap has been found and verified, the application knows the position of the wheel at the time of the last tooth edge. The Angle Clock can now be initialized with this angle. There are two considerations for the systems engineer at this point. First, if the application is synchronizing to a 720 degree cycle, there may or may not be sufficient information to determine the correct half of the engine cycle. Additional information might be required to completely synchronize the Angle Clock to the wheel. Second, there is typically some time lost between the detection of the last edge and the software conclusion that the wheel angle is verified. If the Angle Clock is arbitrarily started at this time, there may be some error in the indicated angle. If the Angle Clock is required to track a 720 degree cycle, then it is possible that the information on which half of the cycle the gap was detected is not yet available to the application. While full synchronization may not have been achieved, the application can declare “Half_Sync.” This means that the crank shaft position is known but the cam shaft position may subsequently require the shaft angle to be corrected by 360 degrees. In an automotive application, Half_Sync is sufficient to operate the engine using a wasted spark and split fueling strategy. If the system is operated in a half sync mode until full sync is possible, it is important to consider the effect on the system of the Angle Clock getting a sudden 360 degree correction if this should be required. Various cam shaft detection strategies may be used to effectively eliminate the cam uncertainty at the time the crank shaft is synchronized. If such a strategy is available, Half_Sync is not required. When synchronization is verified, the angle at the last tooth edge is known. The software should immediately write that angle to TCR2, write the TRR value derived from the last period, and start the Angle Clock. The first series of ticks will be delayed by the latency of the function to this point, but if necessary the Angle Clock will go into High Rate mode at the next tooth edge to catch up. 3.4 Anomalies There are two ways to minimize the effects of anomalies that can cause loss of synchronization in the eTPU Angle Clock: prevent as many as possible, and provide a means to detect and correct those that cannot be prevented. The prevention is typically done by the eTPU hardware system, properly setup by the software. However, once an anomaly is detected and processed by the system either as a superfluous or a missing Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 15 System Design tooth edge signal, the Angle Clock design can only help detect the problem, and pass the information on to the host for corrective action. 3.4.1 Error Prevention The eTPU Angle Clock provides means to reject tooth edges detected outside of certain limits. This rejection is done by an input pin hardware filter and by gating the tooth signal with a match registers in the channel. The TCRCLK input pin filter for the Angle Clock can use the input pin filters of the other eTPU channels, or it can be programmed separately. These filters are designed to reject very short apparent pin transitions such as might be caused by high frequency induced noise. In any case, this low pass filtering of the tooth signal will introduce a time delay in the signal from the tooth. Since the filter time is generally in the order of a few system clock times, the angle represented by this delay is very small even at high wheel speeds. See the Reference Manual for details of the TCRCLK filter. When Channel 0 is in one of the m2_ modes, the MatchA register can be used as a blocking timer for input signals. In this mode, the eTPU software can provide a blanking time after the detection of a tooth edge, during which time a (presumably spurious) additional edge will be blocked. This feature is particularly useful when an imperfect tooth detection circuit presents a chopped or hashed edge to the eTPU, which often happens at low speed. If the frequency of the edge noise is lower than the pin filter rejection, a noise pulse could be detected and counted as a tooth edge signal unless this blanking is used. The blanking match can be programmed as an absolute time or calculated by the eTPU as a percentage of the previous period. The choice depends on the expected characteristics of the edge noise. If a noisy edge is possible, then a noisy return edge might also be detected as an active transition. If blanking is used to prevent noise from being processed as a tooth edge, then the blanking must be applied to both edges of the tooth signal. If a tooth signal is completely lost to the eTPU channel by some means, the hardware alone cannot distinguish the long period from any other deceleration. However, a second match can be setup in Channel 0 to request service if a transition has not occurred within a specified time. 3.4.2 Error Recovery The tick counter in the eTPU Angle Clock ensures that there are exactly TICKS counts between physical teeth. If the Angle Clock acquires an error less than one tooth count, the only possible reason is a software error. Nevertheless, if even if the count acquires a small error, the count will rectify when the LAST tooth is processed. NOTE The most common cause of a small TCR2 angle error is writing the initial angle to the angle clock when synchronization occurs. When gap synchronization is first verified, if the tick rate timer expires just as the TCR2 value is incremented by the tick counter, the tick counts for subsequent teeth count may fall short by one tick until the last tooth re-synchronizes the tick counter. Using the eTPU Angle Clock, Rev. 0 16 Freescale Semiconductor System Design All other sources of error for the Angle Clock involve detecting an extra tooth or missing one which should have been detected. The angle clock hardware cannot automatically correct a tooth detection error. If a lost or extra tooth error is possible, the application software must provide some means to detect the error. The most obvious method is to continually monitor the position of the gap by repeating the gap detection and verification algorithm. If the gap is detected at the wrong tooth position, or not detected at the expected one, the angle count can be corrected. The decision to correct an apparent error can be made in the CPU or the eTPU software, although prudence dictates that the decision is left to the more powerful host processor. The eTPU Angle Clock provides two features to correct a TCR2 counter that has become untracked by one tooth. Each of these corrections can be repeated to make a multiple tooth correction. 3.4.2.1 Inserting a Tooth If the Angle Clock hardware has missed counting a tooth, the software can assert IPH in the TPR to add a single tooth. The effect of this assertion is to force the eTPU to recognize a physical tooth immediately. If the tick counter is in Halt mode, the Angle Clock counts the inserted tooth, then begins a new sequence of tick counts exactly as if a tooth had been detected by the channel. If the tick counter is in Normal mode, it immediately goes into High Rate mode until the tick count is complete, then the inserted count is counted as a physical tooth, and finally the Angle Clock returns to Normal mode. Note that if IPH is asserted when the Angle Clock is in High Rate mode, it will be ignored. The effect of inserting a tooth is that the angle clock will advance the angle count by one tooth without missing any ticks. If a match is scheduled for an angle between the asserting of IPH and the time the count is rectified, it will occur. NOTE Asserting IPH (except when asserted during High Rate mode) will always add exactly one tooth to the TCR2 angle count. The correction will be made using the High Rate mode, and no count will be skipped. 3.4.2.2 Deleting a Tooth If the Angle Clock hardware has mistakenly counted an extra tooth, the software can assert HOLD in the TPR to stop the count for exactly one tooth count. The effect of this assertion is to stop the tick count immediately until the next tooth is detected. When that tooth is detected, the tick counter continues where it left off, meaning that the tick count will count a portion of TICKS before the assertion of HOLD, and the balance after the next tooth. Do not use IPH to cancel a HOLD in progress. To correct the correction, simply negate HOLD. NOTE Asserting HOLD will always subtract exactly one tooth from the TCR2 angle count. The correction is made by stopping the count, and the angle count does not decrement or repeat any count. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 17 eTPU Software Design 3.5 Tooth Circuit Failure If the tooth circuit fails and the failure is detected by the host, the software may implement a limp home strategy. The eTPU Angle Clock provides a method to disconnect the Angle Clock system from the Channel 0 input so that spurious signals from the tooth circuit will not disrupt the limp home system. In that event, the host may configure the eTPU such that Channel 0 continues to monitor the tooth circuit for diagnostic purpose. See the Reference Manual for details. 4 eTPU Software Design The software shown below is taken from an Automotive Reference Design which demonstrates the operation and application of the eTPU Angle Clock in a practical automotive engine control system. Code that is directly copied is displayed in Courier New font. The Reference Design is free to customers and can be obtained from Byte Craft, Ash Ware, or your Freescale representative. 4.1 Host Setup The host must setup the registers and parameters in the eTPU to enable the Angle Clock. In addition to the setup required for any eTPU operation, use of the Angle Clock requires the following steps. a) The Angle Mode bit in the ETPUTBCR must be set. b) The TCRCLK Filter Mode must be setup. c) Initial Channel 0 parameters must be written. d) Channel 0 must be initialized. e) The TCR2 Clock Source in the ETPUTBCR must be set for rising or falling edges to match the IPAC setting for the tooth in Channel 0. The last step may be delayed until Channel 0 has confirmed synchronization. Using the eTPU Angle Clock, Rev. 0 18 Freescale Semiconductor eTPU Software Design 4.2 State Machine Description Table 1shows a simplified state table for an Angle Clock system, similar to the implementation in the Reference Design. The states are referenced in the following description of an angle clock system implementation. Reference Name InitializeCrank Action TICKS = TicksPerToot - 1 Exit Condition GoTo State State Table 1. Angle Clock System State If ActiveEdge ToothCount = 0 CrankStatus = Stall; First_edge CrankStatus = WaitingGap If timeout (StallTimer) StallTimer = StallPeriod at startpoint Time(activeEdge) If ActiveEdge ToothTime = Time(ActiveEdge) First Period StallTimer = StallPeriod at startpoint Time(activeEdge) If ActiveEdge Period = Time(ActiveEdge) - ToothTime If timeout (StallTimer) ToothTime = Time(ActiveEdge) ToothCount += 1 TickRate = Period/TicksPerTooth BlankTimer = Period * BlankingRatio Testing_Possible_Gap StallTimer = StallPeriod at startpoint Time(activeEdge) If Period>GapRatio * PeriodLast PeriodLast = Period If ActiveEdge Period = Time(ActiveEdge) - ToothTime If timeout (StallTimer) ToothTime = Time(ActiveEdge) ToothCount += 1 TickRate = Period/TicksPerTooth BlankTimer = Period * BlankingRatio Apparent_Gap Period = PeriodLast If ActiveEdge TickRate = Period/TicksPerTooth If timeout (StallTimer) Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 19 eTPU Software Design Reference Name PossibleGapVerifying Action Exit Condition StallTimer = StallPeriod at startpoint Time(activeEdge) If Tooth_Period*Gap_Rati o < PeriodLast PeriodLast = Period If Active Edge Period = Time(ActiveEdge) - ToothTime If timeout (StallTimer) GoTo State State Table 1. Angle Clock System State (continued) ToothTime = Time(ActiveEdge) ToothCount += 1 TickRate = Period/TicksPerTooth BlankTimer = Period * BlankingRatio GapVerified CrankStatus = HalfSync If ActiveEdge ToothCount = AngleSync/TicksPerTooth If timeout (StallTimer) Period = PeriodLast TickRate = Period/TicksPerTooth BlankTimer = Period * BlankingRatio EngineAngle = AngleSync Counting StallTimer = StallPeriod at startpoint Time(activeEdge) If ToothCount == ToothBeforeGap PeriodLast = Period If ActiveEdge Period = Time(ActiveEdge) - ToothTime If AdjustAngle() //return ToothTime = Time(ActiveEdge) If timeout (StallTimer) ToothCount += 1 If Receive(Signal) 12 if (ToothCount == LastRealTooth) then LAST = true TickRate = Period/TicksPerTooth BlankTimer = Period * BlankingRatio Gapping MISSCNT = NumberMissing If ActiveEdge if ((FirstGap && !CamDetected)||(SecondGap && CamDetected) then CrankStatus = Full_Sync else CrankStatus = Error If AdjustAngle() //return StallTimer = (StallPeriod + NumberMissing* Period) at startpoint Time(activeEdge) If timeout (StallTimer) BlankTimer = Period * (NumberMissing + BlankingRatio) Using the eTPU Angle Clock, Rev. 0 20 Freescale Semiconductor eTPU Software Design Reference Name NewRev AdjustAngle Action Exit Condition if AngleClock = 0 then ToothCount = 0 If ActiveEdge ToothTime = Time(ActiveEdge) If AdjustAngle() //return BlankTimer = Period * BlankingRatio If timeout (StallTimer) EngineAngle = EngineAngle + AngleCorrection Return to last state. GoTo State State Table 1. Angle Clock System State (continued) x Do Not Change State Number 4.2.1 Initialize Crank The first state is entered by a host service request. The eTPU parameters are initialized and hardware is setup for the specific application. EXAMPLE if (hsrInitAngleClock) // Sets Entry Vector for the eTPU { /* Initialize Parameters */ State1: // Set the channel mode to detection one input transition and two match events SetChannelMode(m2_st); /* ... */ // Setup action unit A to capture high to low transition SetupCaptureTrans_A(Capture_tcr1, high_low); /* Match2SingleTransition mode requires a MatchA before the transition can be detected. Force the first match in a couple of microseconds. */ // Setup match to block out transition too close to current time SetupMatch_A((tcr1+20), Mtcr1_Ctcr1_ge, match_no_change); } 4.2.2 First Edge The eTPU will wait until a transition is detected on the input pin. The channel service request vector for TransitionA is shared with Match B. Also, the channel cannot distinguish between the initial startup tooth transitions and subsequent ones. Therefore the software must sort out the service requests from the channel when they are received. EXAMPLE Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 21 eTPU Software Design else if (matchB_transA) //Here on MatchB (stall) or TransitionA (Tooth edge) { if (IsTransALatched()) //If the Tooth edge is detected { /* Do some common tasks... */ switch(Last_State) { case InitializeCrank: // State 2 CrankStatus = Waiting_Gap; SetChannelInterrupt();//Inform the host that the crank status is updated Last_State = First_edge; break; /* Additional cases inserted here */ } // end of Switch...case statement // The transition capture only need to setup once at init. // Clear transition latch will re-arm the transition detection ClearTransLatch(); // Setup match event to block out input trans too close to the valid falling edge. // The transition detection is disabled until the match event on the action unit A occur. SetupMatch_A((EdgeCaptureTime + ToothPeriod*BlankingRatio), Mtcr1_Ctcr1_ge, match_no_change); // Setup match event to detect stall condition // If the crank edge transition does not occur again for a StallPeriod, it is stalled SetupMatch_B((EdgeCaptureTime + StallPeriod), Mtcr1_Ctcr1_ge, match_no_change); } // active edge Using the eTPU Angle Clock, Rev. 0 22 Freescale Semiconductor eTPU Software Design 4.2.3 First Period When the second edge is detected, the function can make the first measurement of the tooth period. The period should be stored as a global variable, as it is the best measure of the wheel speed and may be used by other drivers. Before it is overwritten, the previous period should be stored off for use in detecting the gap. 4.2.4 Testing for a Possible Gap When the third edge is detected, enough information finally exists to test for the missing tooth gap. This routine is now the default for subsequent teeth. This state is repeated until the gap test is satisfied after which a confirming test needs to performed on the following period. It is necessary from this point on to count the teeth that are detected. For example, if a 36-1 tooth wheel produces more than 35 tooth periods without a gap detection, an exception might be raised with the host. Typically the tooth count is rectified when the first gap is detected. After that, the software can anticipate subsequent gap detections. If the wheel is to be tracked over 720 degrees as is necessary for a four-cycle automotive engine, a separate search needs to be conducted for the unique cam information indicating which of the two crankshaft cycles are currently being tracked. Note that the cam information and the crank synchronization are both needed to determine full synchronization. In addition to tracking the tooth period and count, the angle clock software should provide status to the host and other applications using the angle information. The status selections might include: 1. Stall indicates that the Angle Clock has not yet determined a valid period, or the time since the last tooth transition exceeded a specified limit. 2. Searching_Gap is used to indicate that teeth have been detected at an acceptable rate, but the first gap has not yet been detected and confirmed. 3. Half_Sync in a 720 degree system indicates that the gap has been verified, but the cam cycle information has not been determined. 4. Full_Sync indicates that the TCR2 counter is synchronized with the wheel and the cam shaft. 5. Error indicates that the Angle Clock system has detected an incorrect state change. Note that in a four-cycle engine, some limited operation is possible in Half_Sync mode. EXAMPLE case Testing_Possible_Gap: { ToothPeriodLast = ToothPeriod; ToothPeriod= TempToothPeriod; ToothTime = EdgeCaptureTime; ToothCount = ToothCount + 1; if (ToothPeriod > (ToothPeriodLast*GapRatio + ToothPeriodLast)) Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 23 eTPU Software Design { Last_State = Apparent_Gap; } else { Last_State = Testing_Possible_Gap; /* if the test fails, we continue testing... */ } break; 4.2.5 Apparent Gap When the gap test is satisfied it may be necessary to confirm the fact by testing the period of the following gap. 4.2.6 Possible Gap Verifying One possible means to verify a probable gap is to determine that the period following appears to be shorter by a test similar to the one used to find the gap. The algorithm and parameters used for gap detection and verification must satisfy the requirements for the target system. If the gap is not verified, the system must return to the Testing for a Possible Gap state. EXAMPLE case Apparent_Gap: ToothPeriodLast = ToothPeriod; ToothPeriod= TempToothPeriod; ToothTime = EdgeCaptureTime; ToothCount = ToothCount + 1; if (ToothPeriod >= ToothPeriodLast*GapRatio)//verify { CrankStatus = Half_Sync; SetChannelInterrupt();//Inform the host that the crank status is updated ToothCount = 1; /* More */ Last_State = GapVerified; } else Using the eTPU Angle Clock, Rev. 0 24 Freescale Semiconductor eTPU Software Design Last_State = PossibleGapVerifying; /* More */ break; 4.2.7 Gap Verified Once the gap is verified, the system can go to Half_Sync or even Full_Sync mode. The tooth position is now known, and subsequent gaps can be anticipated. An angle can be written to the TCR2, although if the mode is Half_Sync, the angle could be off by 360 degrees. 4.2.8 Counting Once wheel sync has been achieved, the Angle Clock system executes repeated cycles of tooth detection and period timing, driving the TCR2 in wheel synchronization. The rate of the ticks following a tooth are extrapolated from the previous period by the software when it programs the Tick Rate register. The Tick Rate register is organized as a 15-bit whole number and a 9-bit fraction and is programmed in terms of TCR1 counts. The eTPU can automatically capture the TCR1 time of each tooth edge, so the period is trivial to determine. The new edge time is then stored for the next period calculation. To determine the tick period, the software need only divide the measured tooth period by the number of tick counts per tooth. This division can present some problems for the designer depending on the selected resolution of TCR1 and the speed range of the wheel. See Section 3.1.3, “Angle Resolution.” Even when the TCR1 is properly selected, the software engineer needs to ensure that the intermediate result of the fixed point calculation does not overrun a register or truncate needed resolution of the tick rate. At low wheel speeds, the period is long and a left shift can be done after dividing by the ticks per tooth. If the shift is done before the division, the value may overflow. However, at high speeds, the period is short and dividing by the ticks per tooth could result in gross errors before the shift is done. The algorithm in the example below is designed to implement the 9-bit shift in two steps to minimize loss of resolution. EXAMPLE if (IsTransALatched()) //If the Tooth edge is detected { EdgeCaptureTime = GetCapRegA();//Capture the edge transition time TempToothPeriod = EdgeCaptureTime-ToothTime; ToothTime = EdgeCaptureTime; TempTicks = ((TempToothPeriod*8)/TicksPerTooth)*64;// left shift by 9 bits and a div by 60 implements a TickRate = TempTicks; NOTE The value in the Tick Rate Register must never be programmed to less than 1.0. If the integer value is set to 0, it will be interpreted as 32768. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 25 eTPU Software Design The Angle Clock tick counter begins timing out when the tooth edge occurs. The calculation of a new value for the Tick Rate Register will take some time to complete. While this is being done the old value is used for the tick rate. At steady state this makes no difference, but when the wheel is accelerating, the first tick is necessarily late. If the acceleration continues, all of the tick counts will be late and the Angle Clock will have to go into High Rate mode to catch up. It is possible to compensate for the accelerating wheel by adjusting the tick rate so that the next tooth is counted a bit faster than a simple extrapolation. This adjustment can be added to the software design at the engineer’s discretion. This state is repeated for each new tooth detection until one of the following occurs: 1. The tooth count indicates that the gap is following next. 2. The tooth count indicates that the next tooth is the zero angle reference point. 3. The host requests service, for example to correct an error. 4. The following tooth is not detected within a specified time (stall). 4.2.9 Gapping When the tooth count indicates that a new gap is expected, the system must verify that measured gap times pass the designated test. If the gap is correctly placed, no host action is required. If the gap period is outside the range of acceptability, the information should be passed up to the host by setting the status to Error. The application can then analyze the error and execute a correction procedure. NOTE Once synchronized, the Angle Clock system can proceed indefinitely without further host action, unless a signal anomaly occurs. 4.2.10 New Revolution When the count of the teeth indicates that the last tooth in the cycle has been detected, and if the system required a periodic angle count, the software must set the LAST bit so that the counter will reset at the next detected tooth edge. Note that the counter reset will not occur on a tooth count inserted by MISSCNT during the gap, although asserting the IPH when LAST is set will reset the TCR2. In a 720 degree system, this point occurs every second revolution of the wheel. The phasing of the count may be done automatically (for example, by using a cam detected signal to enable the reset logic) or manually by having the host force Full_Sync based on the cam information. 4.2.11 Adjust Angle Provision may be made in the Angle Clock software for the host to alter the angle indicated by the TCR2 counter. This action could be taken as a result of an independent determination that the counter fell out of sync, perhaps as a result of detecting a spurious tooth. The system can use IPH or HOLD to advance or retard the angle count by one tooth. Remember to correct the tooth count as well so that the next reset occurs at the correct tooth position. When the Adjust Angle service request is processed, the function Using the eTPU Angle Clock, Rev. 0 26 Freescale Semiconductor Angle Clock Application should revert to Full_Sync mode. If the correction is made in error, the system software will indicate this at the next gap. 4.2.12 Stall Provision should be made to detect the cessation of the tooth signals. Typically the system resets a match timer at each tooth edge, and reverts to a Stall status if the timer expires before the next tooth is detected. 5 Angle Clock Application The Angle Clock was implemented in the Reference Design with little more software than is listed in this section. Several variations of the Angle Clock software have been written for various applications. Freescale provides the Reference Design with a complete working angle clock and several drivers free to customers. See your Freescale representative. As described above, the eTPU Angle Clock can implement a free running angle counter or a periodic wheel angle indicator. Each alternative has advantages as well as problems, which are discussed briefly below. 5.1 Free Running Angle Counter If the LAST bit is not set periodically by the Angle Clock software, the wheel angle will accumulate 16777215 ticks then roll over to zero. If this is applied to a 60-2 tooth wheel with 60 ticks per tooth, each revolution of the engine will increment the count by 0xE10 (3600) counts. Thus a specific point on the wheel which is represented by 0xABC in TCR2 will on the next revolution be represented by 0x18CC, and on the next cycle by 0x26DC. In order to find the absolute position on the wheel at any time, the software must subtract the angle at some reference point from the indicated angle. While this seems tedious, the free running angle counter offers one clear advantage: match comparisons for angles can be done using the greater-or-equal compare. Any angle which previously occurred up to about 2300 revolutions in the past can be immediately matched with respect to the current angle. However, if a free running angle counter is used, each system function using the angle needs to use the reference point to schedule or capture a channel action. If spark is to be scheduled for 12 degrees before top dead center (BTDC), the spark driver function needs to know a reference point in order to program the correct TCR2 value into the match register. In general the host software may change the spark angle at any time. If a change is made which would require a spark to occur in the past, the greater-or-equal compare would trigger a match immediately. The free running counter design is much simpler if the number of teeth on the wheel and number of ticks between the teeth were each powers of 2. For example, if a 64-2 tooth wheel was used in a system with 128 ticks per tooth, the number of ticks per revolution would be 64 (0x40) times 128 (0x80) or 8192 (0x2000). In this case the counter would count exactly 2048 (0x800) revolutions and roll over. The TCR2 counter value would simply be a concatenation of an 11-bit revolution number, a 6-bit tooth number, and a 7-bit tick number. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 27 Angle Clock Application 5.2 Periodic Angle Clock The obvious advantage of the periodic angle clock is that there is a one-to-one correspondence between the TCR2 value and the instantaneous angle of the wheel, regardless of the tooth and ticks configuration. The angle can be read at any time both by the host and by the eTPU functions. Periodic matches are always programmed with the same value. However, the greater-or-equal compare in the channel match registers will not function properly with a periodic angle counter. For example, an angle of 719 degrees will always test greater than 0 degrees. In an equals-only setup, when a function sets up a channel for action at a future angle, that angle can be any value in the range of the Angle Clock and the match will occur in the next occurrence of that angle. This is true even if the angle is 719 degrees in the future. The corollary of this is that if a system update results in a decision that an action that was scheduled should occur in the past, the match will wait until the next revolution. NOTE In the eTPU Angle Clock, no counts will be skipped. Any in-range equals-only match will always be satisfied on the next occurrence of the angle. The discrimination between reprogramming to the past rather than the future is left to the eTPU software. The designer must insure that, for example, if a spark is about to occur and the spark fire angle is updated to occur at an earlier angle, the match is forced immediately. If the earlier angle is simply written to the match register, the spark will be missed until the next cycle. There is one additional situation to consider when using equals-only matches with the angle clock. If the tick rate is slow, it is possible to get a service request on an angle match and execute part of a thread before the angle changes. If a function is trying to set up a future match exactly 360 (or 720) degrees after the current one, care must be taken that the register is not written with the current value of TCR2. Please refer to the Reference Design for examples of how to use a periodic Angle Clock. 5.3 Angle Math If the Angle Clock is used in the continuous angle mode, angles parameters can be added, subtracted, and compared like any other 24-bit integer. However, when the user selects a periodic reset of the Angle Clock, modulus arithmetic must be used. If the Angle Clock is reset every cam revolution (= two crank revolutions), the modulus is 720 degrees expressed in terms of the tick resolution. For example if a 60-tooth wheel is used with 60 ticks per tooth, there would be 7200 ticks per cam cycle (Ticks_Per_Cycle). Adding two angles in such an application would be done thusly: New_Angle = (First_Angle + Second_Angle) % Ticks_Per_Cycle; This operation is mathematically correct, but it might not generate the most efficient code. This is because the modulus is normally generated as a divide instruction. A more efficient coding would be to add the numbers, and if the sum is greater than Ticks_Per_Cycle, subtract Ticks_Per_Cycle. Macros or subroutines for handling this math can be found in the Reference Design. Using the eTPU Angle Clock, Rev. 0 28 Freescale Semiconductor Summary 6 Summary The eTPU is particularly suited to applications where input and output actions are synchronized to the position of a rotating wheel. The eTPU Angle Clock provides hardware which, when combined with the proper software, can track the wheel angle through accelerations, decelerations, and a wide range of speeds. If a wheel is tracked by the eTPU Angle Clock, many output matches and input captures can operate on an angle count as well as a time count, and even on combinations of the two. Compensations for speed changes are made in the Angle Clock only. An angle-triggered event will occur on the best estimate of the match angle. The Angle Clock is complex to set up, but when running it offers an excellent integration of fast operating hardware with the complex control of a software program. A Reference Design has been built to demonstrate the operation of a periodic angle clock with other engine control functions. See your Freescale representative for details. Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 29 THIS PAGE INTENTIONALLY LEFT BLANK Using the eTPU Angle Clock, Rev. 0 30 Freescale Semiconductor THIS PAGE INTENTIONALLY LEFT BLANK Using the eTPU Angle Clock, Rev. 0 Freescale Semiconductor 31 How to Reach Us: Home Page: www.freescale.com E-mail: [email protected] USA/Europe or Locations Not Listed: Freescale Semiconductor Technical Information Center, CH370 1300 N. Alma School Road Chandler, Arizona 85224 +1-800-521-6274 or +1-480-768-2130 [email protected] Europe, Middle East, and Africa: Freescale Halbleiter Deutschland GmbH Technical Information Center Schatzbogen 7 81829 Muenchen, Germany +44 1296 380 456 (English) +46 8 52200080 (English) +49 89 92103 559 (German) +33 1 69 35 48 48 (French) [email protected] Japan: Freescale Semiconductor Japan Ltd. Headquarters ARCO Tower 15F 1-8-1, Shimo-Meguro, Meguro-ku, Tokyo 153-0064, Japan 0120 191014 or +81 3 5437 9125 [email protected] Asia/Pacific: Freescale Semiconductor Hong Kong Ltd. Technical Information Center 2 Dai King Street Tai Po Industrial Estate Tai Po, N.T., Hong Kong +800 2666 8080 [email protected] For Literature Requests Only: Freescale Semiconductor Literature Distribution Center P.O. Box 5405 Denver, Colorado 80217 1-800-441-2447 or 303-675-2140 Fax: 303-675-2150 [email protected] Information in this document is provided solely to enable system and software implementers to use Freescale Semiconductor products. There are no express or implied copyright licenses granted hereunder to design or fabricate any integrated circuits or integrated circuits based on the information in this document. Freescale Semiconductor reserves the right to make changes without further notice to any products herein. Freescale Semiconductor makes no warranty, representation or guarantee regarding the suitability of its products for any particular purpose, nor does Freescale Semiconductor assume any liability arising out of the application or use of any product or circuit, and specifically disclaims any and all liability, including without limitation consequential or incidental damages. “Typical” parameters that may be provided in Freescale Semiconductor data sheets and/or specifications can and do vary in different applications and actual performance may vary over time. All operating parameters, including “Typicals”, must be validated for each customer application by customer’s technical experts. Freescale Semiconductor does not convey any license under its patent rights nor the rights of others. Freescale Semiconductor products are not designed, intended, or authorized for use as components in systems intended for surgical implant into the body, or other applications intended to support or sustain life, or for any other application in which the failure of the Freescale Semiconductor product could create a situation where personal injury or death may occur. Should Buyer purchase or use Freescale Semiconductor products for any such unintended or unauthorized application, Buyer shall indemnify and hold Freescale Semiconductor and its officers, employees, subsidiaries, affiliates, and distributors harmless against all claims, costs, damages, and expenses, and reasonable attorney fees arising out of, directly or indirectly, any claim of personal injury or death associated with such unintended or unauthorized use, even if such claim alleges that Freescale Semiconductor was negligent regarding the design or manufacture of the part. Freescale™ and the Freescale logo are trademarks of Freescale Semiconductor, Inc. All other product or service names are the property of their respective owners.© Freescale Semiconductor, Inc. 2004. All rights reserved. AN2897 Rev. 0 11/2004