AN239 Bit Banged LIN Slave Node for PIC16 & PIC18 Author: Ross Fosler Microchip Technology Inc. INTRODUCTION The Local Interconnect Network (LIN), as described in the LIN v1.2 specification, is a multi-layered system. The levels vary from the physical interface up to the high level application. This application note focuses on the implementation of a low level driver, essentially an interface between the physical hardware connection and the higher level application firmware. Specifically, this application note presents a generic ‘bit banged’ LIN slave driver for both the PIC16 and PIC18 family of PICmicro® microcontrollers. There are many details to this firmware design; however, this application note focuses mainly on how to set up and use the driver. Therefore, the LIN system designer should be able to get an application running on LIN quickly without spending significant time on the details of LIN. Some information about the firmware design is provided at the end of this document for the curious designer who wants to learn a little more about LIN and this driver implementation. The reader should note information in this application note is presented with the assumption that the reader is familiar with LIN specification v1.2, the most current specification available at the time this document was written. Therefore, not all details about LIN are discussed. Refer to the References section for additional information. APPLICATIONS The first question that must be asked is: “Will this driver work for my application?” The next few sections can help those who would like to know the answer to this question and quickly decide whether this is the appropriate driver implementation for their application. The important elements that have significant weight on the decision include available process time, resource usage, and bit rate performance. 2002 Microchip Technology Inc. Process Time Available process time is dictated predominately by bit rate, clock frequency, and code execution. Since code execution varies depending on the state within the LIN driver and there being many states, generating a single equation for process time is unrealistic. A much simpler solution is to test the process time. Figure 1 shows the approximate average available process time for a node running at 8 MHz. FIGURE 1: AVAILABLE PROCESS TIME @ 8 MHz 80% 70% 50% 4.8K 9.6K 19.2K When the LIN bus is IDLE, the driver uses significantly less process time. Although dependent on the same conditions stated above, the used process time is extremely low. At 8 MHz, the average available process time is greater than 98%. Resource Usage A few of the hardware resources are used to maintain robust communications and precise timing. Timer0 is used for maintaining communications timing and bus activity time. In addition, the timer prescaler is adjusted under various conditions to simplify the code and improve performance in many states of the driver. An external interrupt is used for START edge detection for each received byte; either an interrupt-on-change pin, or the INT pin can be configured as the interrupt source. DS00239A-page 1 AN239 Bit Rate In summary, this basically means the PIC16 and PIC18 bit banged drivers are well suited for applications that do not require excessive firmware processing and tight timing. There are a number of peripherals available for the PIC16 and PIC18 devices that can enhance the application without extensive firmware. Some of these include A/D, PWM, USART, and comparators. Also, the PIC18 devices do have an advantage in that they have an extra interrupt vector and hardware stack management capability. Some applications could include motor control, sensor feedback, on/off control, and indication. By selecting the appropriate clock frequency, the driver is designed to operate over the specified operating range of LIN: 1000 bps to 20000 bps. Note, however, that the clock must be selected such that at least 70 instructions can be executed per every bit received. Refer to Figure 2 for recommended operating regions. Summary The driver is designed almost entirely in firmware. Only the hardware peripherals standard to PIC16 and PIC18 MCUs are used. Thus, all communications and timing required by the LIN specification are controlled in firmware. This implies a certain percentage of software resources are consumed, most importantly, time. To put this into perspective, at 19.2 Kbps using an 8 MHz oscillator source, an average of 50% of the process time is used by the driver. Also, given the intolerance to uncertainty, interrupts (high priority for PIC18) should be restricted to the LIN communications driver when the instruction rate to bit rate ration (FOSC/B) is small (i.e., less than 200). For PIC18 devices, the low priority interrupt vector is available since low priority interrupts do not interfere with high priority interrupts. FIGURE 2: RECOMMENDED OPERATING REGIONS Clock Frequency 6 MHz HS Mode Operation(1) 4 MHz XT, and INTRC(1) No Operation 2 MHz 1.2k 7.2k Bit Rate 14k 20k Note 1: Check specific device for available Oscillator modes. DS00239A-page 2 2002 Microchip Technology Inc. AN239 SETTING UP FIGURE 3: PROJECT SETUP Now that the decision has been made to use this driver, it is time to setup the firmware and start building an application. For an example, a complete application, referenced in the appendixes for both the PIC16 and PIC18 families, is built with the LIN driver. Here are the basic steps required to set up your project: 1. Setup a project in MPLAB® IDE. Make sure you have the important driver files included in your project: serial.asm, lin.asm, and linevent.asm. 2. 3. 4. 5. Include a main entry point in your project: main.asm. Edit this file as required for the application. Make sure that the interrupt is setup correctly and initialize the driver. Also ensure any external symbols are included. Edit linevent.asm to respond to the appropriate IDs. This could be a table or some simple compare logic. Be certain to include any externally defined symbols. Add any additional application related modules. The example uses idxx.asm for application related functions related to specific IDs. Edit the lin.def file to set up the compile time definitions of the driver. The definitions determine how the driver functions. The Project The first step is to setup the project. Figure 3 shows an example of what the MPLAB project setup should look like. The following files are required for the LIN driver to operate: • • • • • lin.lkr - Linker script file main.asm - Main entry point into the program serial.asm - Serial communications engine lin.asm - LIN driver linevent.asm - LIN event handling table Any additional files are defined by the system designer for the specific application. For example, Figure 3 shows these files labeled as idxx.asm, where xx represents the LIN ID number. This is simply a programming style that separates ID handling into individual objects thus making the project format easier to understand. Other objects could be added and executed through the main module, main.asm, and the event handler. The Main Object The main.asm module contains the entry point into the program, which is where the driver, hardware, and variables should be initialized. To initialize the driver, call the l_init function. The firmware referenced in Appendix B demonstrates this. Also included in this module is the interrupt vector. The serial function is interrupt based; therefore, it must be included at the interrupt vector. The following code demonstrates this for use with PIC16 MCUs. EXAMPLE 1: INTERRUPT VECTOR CODE EXAMPLE _INTERRUPT_V CODE 0x0004 InterruptHandler movwf W_TEMP ;Save swapf STATUS, W clrf STATUS movwf STATUS_TEMP call SerialEngine swapf movwf swapf swapf STATUS_TEMP, W ;Restore STATUS W_TEMP, F W_TEMP, W retfie 2002 Microchip Technology Inc. DS00239A-page 3 AN239 The above example could also be used for PIC18 MCUs; however, PIC18 MCUs have the Fast Register Stack and a different interrupt vector. If the fast register stack is used, then time and space could be saved by eliminating the context save and restore. Definitions There are numerous compile time definitions, all of them located in lin.def, that are used to setup the system. Table 1 lists and describes these definitions. Likewise, the definitions are also listed in Appendix A. Only five of these definitions are critical for getting a system running. They are: • • • • • MAX_BIT_TIME NOM_BIT_TIME MIN_BIT_TIME USE_GP_CHANGE RX_ADVANCE (or RX_DELAY) The first three definitions, the bit time definitions, setup the baud rate and its boundary for communication. The next item depends on the application hardware design. The LIN designer needs to setup an external START edge detection source; the two options are the INT pin or an interrupt-on-change pin. The last, yet very important definition, is the receive advance or delay. The receive advance (or delay) is used to advance (or delay) the time-base to align to the center of the next bit after the START bit. DS00239A-page 4 LIN Events LIN event functions are where the ID is decoded to determine what to do next, transmit, receive, and how much. The designer should edit or modify the event function to handle specific LIN IDs (see Appendix B for an example). One possibility is to set up a jump table. Another option is to set up some simple compare logic. The example firmware uses simple compare logic. ID Modules The application firmware must be developed somewhere in the project, it can be in main or in separate modules; however, from a functional perspective, it does not matter. The example firmware uses separate ID modules for individual handling of IDs and their associated functions. The most important part is to remember to include all the external symbols that are used. The symbols used by the driver are in lin.inc; this should be included in every application module. 2002 Microchip Technology Inc. AN239 TABLE 1: COMPILE TIME DEFINITIONS Definition Name Value Description d'11' Sets the receive break threshold. For low tolerance oscillator sources, this value should be ‘11’, for high tolerance sources, this value should be ‘9’. LIN_ACTVE_TIME_PS b'10001000' The value loaded into the option register when the slave is actively receiving or transmitting on the LIN bus. A prescale value of 1x is ideal for bit rates between 4800 bps and 14400 bps at 4 MHz. LIN_IDLE_TIME_PS b'10010110' The value loaded into the option register when the LIN bus is IDLE. A prescale setting of 128x is the desired choice for the prescaler. LIN_SYNC_TIME_PS b'10010010' The value loaded into the option register when the slave is capturing the sync byte. A prescale setting of 8x is the desired choice for the prescaler. BRK_THRESHOLD MAX_BIT_TIME d'118' The upper boundary bit time for synchronization, which should equal ((FOSC x 1.15) / 4) /(bit rate) – 2 d'39' The maximum allowable time for the header. This value equals ((34 + 1) x 1.4) – 10, and should not be changed unless debugging. MAX_IDLE_TIME d'195' Defines the maximum bus IDLE time; the spec defines this to be 25000 bit times. The value equals 25000 / 128. The 128 comes from the LIN_IDLE_TIME_PS definition. MAX_TIME_OUT d'128' Specifies the maximum time-out between wake-up requests. The LIN specification defines this to be 128 bit times. MIN_BIT_TIME d'87' NOM_BIT_TIME d'102' MAX_HEADER_TIME RC_OSC N/A The lower boundary bit time for synchronization, which should equal ((FOSC x 0.85) / 4) /(bit rate) – 2 The nominal bit time for synchronization, which should equal (FOSC / 4) /(bit rate) – 2 Enables synchronization. Do not use this definition if using a crystal or resonator. RX_ADVANCE 0x10 This is the receive advance. Use this definition to adjust center sampling for high bit rates, 7400 bps or greater at 4 MHz. RX_ADVANCE must not be used in conjunction with RX_DELAY. RX_DELAY 0xF0 The receive delay. Use this definition to adjust center sampling for low bit rates, less than 7400 bps at 4 MHz. For lower bit rates, the delay should be longer. Note, this value is complimented (i.e., 0xF0 is a delay of 16 cycles). RX_DELAY must not be used in conjunction with RX_ADVANCE. IO_MASK_A b'10111111' Logical AND mask of the transmit pin. IO_MASK_O b'01000000' Logical OR mask of the I/O pin. RX_PIN PORTC,7 The receive pin. RX_PIN_DIR TRISC,7 The receive pin direction control. TX_PIN PORTC,6 The transmit pin. TX_PIN_DIR TRISC,6 The transmit pin direction control. TX_PORT USE_GP_CHANGE PORTC N/A 2002 Microchip Technology Inc. The transmit pin port. Use this definition to configure the external interrupt to be a GPIO interrupt on change. The alternative is to use the INT pin. DS00239A-page 5 AN239 USING THE DRIVER The LIN Driver After setting up a project with the LIN driver’s necessary files, it is time to start using the driver. This section presents pertinent information about using the driver. The important information addressed is: The LIN slave driver is a state machine written for foreground processing. Being in the foreground implies the function must be called often enough to retrieve data from the receive buffer within the serial engine. Typically, the best place to call the driver is in the main program loop, and it should be called as often as possible. Thus, if some application level tasks are sufficiently long, then the driver function will most likely need to be called more than once in the main loop. • • • • • • Using the l_rxtx_driver function Handling error flags Handling finish flags State flags within the driver LIN ID events Bus wake-up The source code provided is a simple example on using the LIN driver in an application. FIGURE 4: Figure 4 shows an example of what the main program loop could look like with the call to the l_txrx_driver function. MAIN PROGRAM LOOP WITH CALL TO l_txrx_driver Main ;Main application loop call l_txrx_driver call l_id_02_function ;Check for ID02 (tx) btfsc call LF_RX l_id_00_function ;Check for ID00 (rx) movf btfsc goto LIN_STATUS_FLAGS, W;Handle errors STATUS, Z Main btfsc goto LE_BTO PutLINToSleep ;Was the bus time exceeded? clrf goto LIN_STATUS_FLAGS Main ;Reset any errors Finish Flags There are two flags that indicate when the driver has successfully transmitted or received data. The receive flag is set when data has been received without error. This flag must be cleared by the user after it is handled. Likewise, the transmit flag indicates when data has been successfully transmitted without error. The transmit flag must also be cleared by the user when it is handled. Figure 4 shows an example of checking the flags; the flags are cleared in the calling function (not shown). Error Flags Certain error flags are set when expected conditions are not met. For example, if the slave failed to generate bit timing within the defined range, a sync error flag (LE_SYNC) is set in the driver. Errors are considered fatal until they are handled and cleared. Thus, if the error is never cleared, then the driver will ignore incoming data. Figure 4 shows an example. DS00239A-page 6 Notice that the errors are all contained within a single register. Therefore, the LIN_STATUS_FLAGS register can be checked for zero to determine if any errors did occur. Driver State Flags The LIN driver uses state flags to remember where it is between received bytes. After a byte is received, the driver uses these flags to decide what is the next unexecuted state, then jumps to that state. One very useful flag is the LS_BUSY flag. This bit indicates when the driver is active on the bus; thus, this flag could be used in applications that synchronize to the communications on the bus. The other flags indicate what has been received and what state the bus is in. Refer to Appendix A for descriptions of the state flags. For most situations, these flags will not need to be used within the application. 2002 Microchip Technology Inc. AN239 ID Events and Functions GENERAL INFORMATION For each ID, there is an event function. The event function is required to tell the driver how to respond to the data following the ID. For example, does the driver need to prepare to receive or transmit data? Also, how much data is expected to be received or transmitted? Additional Interrupts For successful operation three variables must be initialized, a pointer to data memory, frame time, and the count, as shown in Figure 5. FIGURE 5: l_id_00 GLOBAL movlw movwf movlw addwf movlw movwf retlw VARIABLE INITIALIZATION l_id_00 ID00_BUFF ;Set the pointer LIN_POINTER 0x20 ;Adjust the frame time FRAME_TIME, F 0x02 ;Set up the data count LIN_COUNT 0x00 ;Read The pointer to memory tells the driver where to store data for receiving or where to retrieve data for sending. The frame time is the adjusted time, based on the number of bytes to expect. Typically, the frame time register will already have time left over from the header, so time should be added to the register. For two bytes, this would be an additional (30 + 1) * 1.4 bit times, or 43; the value 30 is the total bits of data, START bits, and STOP bits, plus the checksum bits. The counter simply tells the driver how much data to operate on. Note that the count must always be initialized to something greater than zero for the driver to function properly. Waking the Bus A LIN bus wake-up function, l_tx_wakeup, is provided for applications that need the ability to wake the bus up. Calling this function will broadcast the wake-up request character. It is possible to add extra interrupts; however, it is not recommended. The driver uses an external interrupt to synchronize timing to the START edge. If additional interrupts are added, then uncertainty is added to the received START edge. Uncertainty in receiving the START edge can severely degrade the maximum bit rate under certain conditions. There is a finite amount of uncertainty that is acceptable for a given bit rate and clock frequency, defined as follows: 4N INS 1 ----- – ( T E1 ( low ) + T E2 ( high ) + 2T ES ) = T w = --------------FOSC BI Without going into too much detail here, the above equation basically derives the maximum number of instructions related to uncertainty in terms of the ideal bit rate and frequency (discussed later in this document). The real question is what instructions can be counted in this uncertainty and the answer is, it depends on the way the code is written for the application. It is also important to note that some uncertainty is already assumed. To be safe (i.e., not sacrifice reliability), avoid adding any extra code to the interrupt unless your instruction rate to bit rate ratio is greater than 200, or the number of instructions added is extremely small. With PIC18 devices, you have the option of using the low priority interrupt vector for additional interrupts. The high priority interrupt should be used for the LIN driver, since it has precedence. The low priority interrupt could be used for any other interrupt source not related to LIN. Definitions Using Prescalars The prescaler definitions are set to achieve bit rates between 4800 bps and 14400 bps, using a 4 MHz clock source. It is possible to adjust these to achieve lower bit rates or higher clock speeds. For example, multiplying all the prescaler values by two would yield much lower bit rates, if desired. The LIN Event Handler Event handling should be as short as possible. If the event handler is long, unacceptable interbyte space may be seen between receiving the ID byte and transmitting data from the slave to the master. Therefore, choose the best method for decoding in your application. If you are only responding to a couple of IDs, then simple XOR logical compares will suffice. If any more IDs are responded to, then use a jump table. A complete jump table uses a significant amount of program memory; however, it is very quick to decode IDs. 2002 Microchip Technology Inc. DS00239A-page 7 AN239 Calling the Driver The Serial Engine The driver is not a true background task, only the serial communication is. Thus, the driver function must be called frequently. There are two potential problems if the driver function is not called frequently enough. The receive buffer could be overrun, thus, the entire packet would be corrupted. Another problem is unacceptable interbyte space during slave to master transmissions. To be safe, ensure the driver function is called at least four times for every byte. The driver function will execute very quickly if there is no action required. The serial engine is interrupt driven firmware. It handles all bit level communication and synchronization. The function requires an external interrupt source configurable to either an interrupt-on-change pin, or the INT pin. Also, Timer0 is used to control asynchronous communication. With the access to the hardware stack on the PIC18 devices, it is possible to make the driver look like it is operating in the background. Essentially, the address of the driver function could be pushed onto the stack upon interrupt. When the serial communications finishes, the address of the driver is pulled off the stack for execution. when driver tasks are finished, control returns to the application. This method is a possibility; however, it is not shown. Advance or Delay After detecting a START edge for a serial byte, there is a finite duration required to set up for the reception of the byte. Depending on the bit rate and frequency, the duration could put the sample point before or after the center of the next received bit. Thus, the advance and delay options are available. The delay is used to hold sampling when the setup duration is shorter than half the bit time. The advance is used to advance the bit time for the next bit when the setup duration is longer than half the bit time. The setup duration also includes the time required to enter the interrupt, thus, the duration depends significantly on how the interrupt is setup. PIC18 MCUs will have a slightly shorter setup time than PIC16 MCUs, since time can be saved by using the fast register stack. IMPLEMENTATION There are five functions found in the associated example firmware that control the operation of the LIN interface: • • • • • LIN Transmit/Receive Driver LIN Serial Engine LIN Timekeeper LIN Hardware Initialization LIN Wake-up DS00239A-page 8 SYNCHRONIZATION Synchronization is performed by stretching the bit rate clock and using the external interrupt to count the edges of the sync byte. After the last falling edge of the sync byte, the time is captured and compared to the maximum and minimum bit time tolerances specified. If within the tolerance, the value is used as the new time-base. TRANSMITTING WITH READBACK The software UART handles asynchronous communications much like a hardware UART; it receives data and generates errors under various conditions. Because the LIN physical layer has a feedback path for data (see Figure 6), the UART also reads back transmitted data. FIGURE 6: SIMPLIFIED LIN TRANSCEIVER VBAT Buffer RX PIC16 LIN bus TX Open Drain The UART is designed to pre-sample before transmitting to capture feedback information. Transmit operations take 11 bit times to accurately capture the last bit in the transmission. SERIAL STATUS FLAGS There are a few flags within the software UART to control its operation and to feed status information to functions outside the UART. The serial status flags are listed and defined in Appendix A. 2002 Microchip Technology Inc. AN239 Transmit/Receive Driver LIN Timers The l_rxtx_driver is a state machine. Bit flags are used to retain information about various states within the driver. In addition, status flags are maintained to indicate errors during transmit or receive operations. The LIN specification identifies maximum frame times and bus IDLE times. For this reason, a timekeeping function is implemented. The timekeeping function works together with the transmit/receive driver and the transmit and receive functions. Essentially, the driver and the transmit and receive functions update the appropriate time, and bus and frame time when called. If time-out conditions do occur, then status flags are set to indicate the condition. STATES AND STATE FLAGS The LIN driver uses state flags to remember where it is between received bytes. After a byte is received, the driver uses these flags to decide what is the next unexecuted state, then jumps to that state. Figure 7 and Figure 8 outline the program flow through the different states. The states and state flags are listed and defined in Appendix A. TX/RX TABLE A transmit/receive table is provided to determine how to handle data after the node has successfully received the ID byte. The table returns information to the transmit/receive driver about data size and direction. STATUS FLAGS Within various states, status flags may be set depending on certain conditions. For example, if the slave receives a corrupted checksum, then a checksum error is indicated through a status flag. Unlike state flags, status flags are not reset automatically. Status flags are left for the LIN system designer to act upon within the higher levels of the firmware. The status flags are listed and defined in Appendix A. 2002 Microchip Technology Inc. Hardware Initialization An initialization function, l_init, is provided to setup the necessary hardware settings. Also, the state and status flags are all cleared. This function can also be used to reset the LIN driver. Wake-up The only time the slave can transmit to the bus without a request is when the bus is sleeping. Basically, any slave can transmit a wake-up signal. For this reason, a wake-up function is defined, and it sends a wake-up signal when called. DS00239A-page 9 AN239 FIGURE 7: RECEIVE HEADER PROGRAM FLOW A Requesting Wake-up? Yes Read Back Test, Set Flags No Test Break, Set Flags No Update Bus Timer Got Break? Yes Build Option Got Sync? No Measure and Test, Set Flags No Test ID, Determine RX or TX, Determine Data Count, Set Frame Timer, Set Flags Yes Got ID? Yes TX B DS00239A-page 10 TX or RX? RX Finish 2002 Microchip Technology Inc. AN239 FIGURE 8: TRANSMIT/RECEIVE MESSAGE PROGRAM FLOW B TX or RX? Test, Set Flags No RX TX Got Whole Message? Read Back? No Test, Set Flags No Test, Set Flags No Test, Set Flags Yes Yes Sent Whole Message? Read Checksum Yes Sent Checksum? Yes Reset State Flags Finish 2002 Microchip Technology Inc. DS00239A-page 11 AN239 FIGURE 9: TIMEKEEPING PROGRAM FLOW Start LIN bus Sleeping? Yes No Update Bus Time Test for Time-out No Active TX/RX? Yes Update Frame Time, Test for Time-out Finish EVALUATING OPERATING REGION SAMPLING It is important to understand the relationship between bit rate and clock frequency when designing a slave node in a LIN network. Therefore, this section focuses on developing this understanding based on the LIN specification. It is assumed that the physical limits defined in the LIN specification are reasonable and accurate. This section merely uses the defined physical limits and does not present any analysis of the limits defined for physical interface to the LIN bus. Essentially, the focus of this section is to analyze the firmware and its performance based on the defined conditions in the LIN specification. The ideal sampling point is assumed to be the center of the incoming bit, as shown in Figure 10. The equations presented in the following sections use this point as the reference. General Information Some general information used throughout the analysis is provided here. DATA RATE VS. SAMPLING RATE There are essentially two rates to compare: the incoming data rate and the sampling rate. The slave node only has control of the sampling rate; therefore, for this discussion, the logical choice for a reference is the incoming data rate, BI. The equations that follow assume BI is the ideal data rate of the system. FIGURE 10: SAMPLING RELATING CLOCK FREQUENCY ERROR TO BIT ERROR The LIN specification refers to clock frequency error rather than bit error. Because of this, the LIN system designer must design the system with like clock sources; however, this is rather impractical. It is more feasible to have clock sources designed for the individual needs of the node. All of the equations in this section refer to bit error, rather than frequency error. The following equation relates frequency error to bit rate error: 1 ---------------- – 1 = EB 1 + EF For very low clock frequency errors, the bit rate error can be approximated by: – E F ≈ E B Thus, a ±2% frequency error is nearly the same bit rate error. DS00239A-page 12 2002 Microchip Technology Inc. AN239 Acceptable Bit Rate Error The LIN specification allows for a ±2% error for master/slave communications. This section evaluates this tolerance based on specified worst case conditions (slew rate, voltage, and threshold) and the implementation. FIGURE 13: IDEAL SAMPLING WINDOW It is relatively easy to see the maximum allowed error in the ideal situation. Ideal is meant by infinite slew rate with a purely symmetrical signal, like the signal shown in Figure 11. FIGURE 11: The LIN specification defines a tolerable slew rate range and threshold. The worst case is the minimum slew rate at the maximum voltage, 1V/µs and 18V, according to the LIN specification. The threshold is above 60% and below 40% for valid data. Figure 13 shows the basic measurements. ADJUSTED BIT TIME ERROR VBAT 60% 40% IDEAL WINDOW VBAT TEI TES Taking the difference of the ideal maximum time and the slight adjustment due to specified operating conditions yields the following error time adjustment: TE Basically, if the data sampling is greater or less than half of one bit time, TE, over nine bits, the last bit in the transmission will be interpreted incorrectly. Figure 12 graphically depicts how data may be misinterpreted because of misaligned data and sampling rates. FIGURE 12: DATA VS SAMPLING Ideal Slow Fast The following two equations give the maximum and minimum bit rates based on shifting time by one-half of one bit time or TE = ±1/(2BI). 1 TE 1 ----- – ------ = -----------BI 9 Bmax 1 TE 1 ----- + ------ = ----------BI 9 Bmin SHORTENED WINDOW DUE TO SLEW RATE 1 ( 0.5V – 0.4V ) T EI – T ES = -------- – --------------------------------- = T E 2B I ( dV ) ⁄ ( dt ) min Therefore, TE is slightly smaller than the ideal case, and the minimum and maximum equations in the previous section yield a slightly narrower range for bit rate. OFFSETS An offset is a less than ideal sample point. For example, it is possible for a software UART to take a sample before or after the center point of an incoming bit, as shown in Figure 14. This is related to an offset from the START edge and ultimately shifts the bit rate error to favor one side over the other. For example, if the START edge detection is delayed for 10 µs from the center of a 9.6 Kbit transmission, the absolute range for bit rate error is -4.1% and +6.9%. FIGURE 14: OFFSET FROM CENTER VBAT 60% 40% TEE TO TEI Although the ideal sampling window may be a useful approximation at very low bit rates, slew rate and threshold must be accounted for at higher rates. The ideal analysis serves as a base for more realistic analysis. 2002 Microchip Technology Inc. DS00239A-page 13 AN239 The example firmware leaves the Timer0 interrupt enabled at all times to maintain some basic time about the LIN bus activity. A side effect of this is unpredictable offset. For example, if a START edge occurs while program execution is in an interrupt, the interrupt routine must finish before the START edge can be Acknowledged. Therefore, an undetermined offset from the START edge occurs. Although the exact offset cannot be determined when interrupts are enabled, it is possible to determine a maximum offset. Basically, the maximum offset is related to the longest time through the interrupt when looking for a START edge. Having the maximum offset leads to the maximum bit rate. The same equations apply as before; however, TE is different for the maximum and minimum bit rate, because there is no time symmetry. 1 T E1 1 ----- – --------- = -----------BI 9 B max 1 T E2 1 ----- + --------- = ----------9 BI Bmin TE1 and TE2 are related: 1 ----- – 2T ES = T E1 + T E2 BI where: FIGURE 15: ABSOLUTE OFFSET WINDOW VBAT 60% 40% TE1(low) Tw TE2(high) The 4/FOSC term is the instruction time. Multiplying the instruction time by the number of executed instructions in the interrupt routine results in the total time through the interrupt. Substituting the time equations TE1(low), TE2(high), and TES, and solving BI yields the maximum bit rate: 0.6399 BI = --------------------------4N ------- – 1.8µs F Adjusting this down by 15% to allow for synchronization tolerances leads to maximum allowable bit rate. For example, for a slave node operating at 4 MHz with a maximum instruction count of 40 through an interrupt, the maximum ideal bit rate would be about 14.2 kbps. Beyond 14.2 kbps, there is a significant probability that incoming data will be misinterpreted. T E2 = T EI – T ES – T O Minimum Samples Per Bit T E1 = T EI – T ES + T O Given a finite bit rate error range and finite control of the bit rate, leads to areas where the slave cannot operate. These are basically gaps where the error is outside the defined bit rate error range for a particular number of instructions per bit. This section provides the mathematical basis for these gaps. The equations developed in this section are provided to help the LIN designer build a robust network. Ultimately, the LIN specification requires that the slave accept as much as a ±2% error between the incoming bit rate (BI) and the sampling bit rate. TE1 and TE2 have specific limits for offsets before and after the center sampling point. They are: – 9 ( – 0.02 ) T E2 ( high ) = -------------------------( 0.98 ) ( B I ) 9 ( 0.02 ) T E1 ( low ) = -------------------------( 1.02 ) ( BI ) With these times, the total window time shown in Figure 15, can be calculated to determine the maximum allowable offset or the maximum interrupt duration: 4N INS 1 ----- – ( T E1 ( low ) + T E2 ( high ) + 2T ES ) = T w = --------------FOSC BI DS00239A-page 14 FREQUENCY RANGE The following equation determines the clock frequency as a function of the number of instructions executed per bit, bit rate, and bit rate error. FOSC = ( EB + 1 ) ( N ) ( 4 ) ( B ) 2002 Microchip Technology Inc. AN239 OVERLAPPING OPERATION For a large number of instructions executed per bit, the slave will synchronize and communicate well with the master. However, for a particular error range, ±2%, with higher bit rates and lower clock frequencies, the slave may never synchronize and communicate. To approach this problem, the minimum frequency for a number of instructions (EL+1)(N)(4)(BI) must be compared to the maximum frequency for one less number of instructions (EH+1)(N-1)(4)(BI). Where these are equal is the border between continuous and discontinuous operation for any given input frequency: ( EL + 1 ) ( N ) ( 4 ) ( B I ) = ( EH + 1 ) ( N – 1 ) ( 4 ) ( B I ) Solving this equation yields: ( EH + 1 ) N low = -----------------------------------------------( EH + 1 ) – ( EL + 1 ) Therefore, the minimum number of instructions, Nlow, must be executed per bit to accept the defined error. For example, for a ±2% error, the lowest number of instructions accepted before certain clock frequency/bit rate combinations become a problem is 26. Note that the value of 26 is much lower than the number of instructions through the interrupt. 2002 Microchip Technology Inc. POSSIBLE ALTERNATE IMPLEMENTATION The bit banged firmware code referenced in this application note utilizes the Timer0 module and an external interrupt. It is also possible to use the CCP and Timer1 module to perform the same function. The results are nearly the same as the implementation presented here. MEMORY USAGE The firmware code size depends on the build conditions. As it is currently built with the example application, the firmware occupies 412 words of program memory and 46 bytes of data memory. REFERENCES LIN Specification Package Revision 1.2, http://www.lin-subbus.org/ MPASM™ User’s Guide with MPLINK™ and MPLIB™, Microchip Technology Incorporated, 1999 DS00239A-page 15 AN239 APPENDIX A: TABLE A-1: SYMBOLS FUNCTIONS Function Name Purpose l_init Call this function to initialize or reset the hardware associated to the LIN interface. l_tx_wakeup Wake-up function. Call this function to wake-up the bus if asleep. l_txrx_driver The core transmit and receive function, which manages transmit and receive operations to the bus. State flags are set and cleared within this function. Status flags are also set based on certain conditions (i.e., errors). l_txrx_table This function is called by the transmit/receive daemon after the identifier byte has been received. Message length and direction is returned to the driver. Within the table, pointers could be set up for different identifiers. SerialEngine This is the interrupt driven software UART. UpdateTimer Used to update the bus and frame timers. TABLE A-2: REGISTERS Variable Name Purpose BUS_TIME Bus timer. FRAME_TIME 8-bit frame timer register. HEADER_TIME Same as FRAME_TIME. LIN_CHKSUM Used by the driver to calculate checksum for transmit and receive. LIN_COUNT Used by the driver to maintain a message data count. LIN_FINISH_FLAGS Contains flags indicating completion of transmit and receive data. LIN_ID Holding register for the received identifier byte. This register is used in the l_txrx_table function to determine how the node should react. LIN_POINTER Pointer to a storage area used by the driver. Data is either loaded into or read from memory depending on the identifier. LIN_READBACK Holding register for transmitted data to be compared with received data for bit error detection. LIN_STATE_FLAGS Flags to indicate what state the LIN bus is in. LIN_STATE_FLAGS2 Additional flags to indicate what state the LIN bus is in. LIN_STATUS_FLAGS Contains status information about the LIN bus. RXDATA The Least Significant Byte of the receive shift register. The data is also pulled from this register after a complete receive. RXSR_2 The Most Significant Byte of the receive shift register. RXTX_COUNT Bit counter register for the software UART. SERIAL_FLAGS This register holds the flags to control the software UART. TIME_BASE This register holds the time per bit based on the number of instructions. TXSR The Most Significant Byte of the transmit shift register. TXSR_2 The Least Significant Byte of the transmit shift register. DS00239A-page 16 2002 Microchip Technology Inc. AN239 TABLE A-3: Flag Name FLAGS Register Meaning LE_BIT LIN_STATUS_FLAGS Indicates a bit error. LE_BRK LIN_STATUS_FLAGS Indicates a failure to receive a valid break. LE_BTO LIN_STATUS_FLAGS Indicates a bus activity time-out error. LE_CHKSM LIN_STATUS_FLAGS Indicates a checksum error during a receive. LE_FTO LIN_STATUS_FLAGS Indicates a frame time-out error. LE_GEN LIN_STATUS_FLAGS Indicates a general error, typically a framing error. LE_PAR LIN_STATUS_FLAGS Indicates a parity error. LE_SYNC LIN_STATUS_FLAGS Indicates a synchronization tolerance error. LF_RX LIN_FINISH_FLAGS Indicates data has been received. LF_TX LIN_FINISH_FLAGS Indicates data has been sent. LS_BRK LIN_STATE_FLAGS Indicates a break has been received. LS_BUSY LIN_STATE_FLAGS Indicates the LIN bus is busy. LS_CHKSM LIN_STATE_FLAGS Indicates the checksum has been sent or received. LS_DATA LIN_STATE_FLAGS Indicates all data has been sent or received. LS_ID LIN_STATE_FLAGS Indicates the identifier has been received. LS_RBACK LIN_STATE_FLAGS Indicates a read back is pending. LS_SLPNG LIN_STATE_FLAGS Indicates the LIN bus is sleeping. LS_SYNC LIN_STATE_FLAGS Indicates a sync byte has been received. LS_TXRX LIN_STATE_FLAGS Indicates transmit or receive operation. LS_WAKE LIN_STATE_FLAGS Indicates a wake-up has been requested (this node only). S_BUSY SERIAL_FLAGS Indicates whether the serial engine is busy or not. S_FERR SERIAL_FLAGS Indicates an invalid STOP bit was received. S_RXIF SERIAL_FLAGS Indicates data has been received. S_SSRT SERIAL_FLAGS Indicates the serial engine is waiting for a start of sync. S_SYNC SERIAL_FLAGS Indicates the serial engine is syncing. S_SYNCERR SERIAL_FLAGS Indicates a failure to sync. S_TXRX SERIAL_FLAGS Indicates the UART is transmitting or receiving. 2002 Microchip Technology Inc. DS00239A-page 17 AN239 TABLE A-4: COMPILE TIME DEFINITIONS Definition Name Value Description d'11' Sets the receive break threshold. For low tolerance oscillator sources, this value should be ‘11’, for high tolerance sources this value should be ‘9’. LIN_ACTVE_TIME_PS b'10001000' The value loaded into the option register when the slave is actively receiving or transmitting on the LIN bus. A prescale value of 1x is ideal for bit rates between 4800 bps and 14400 bps at 4 MHz. LIN_IDLE_TIME_PS b'10010110' The value loaded into the option register when the LIN bus is IDLE. A prescale setting of 128x is the desired choice for the prescaler. LIN_SYNC_TIME_PS b'10010010' The value loaded into the option register when the slave is capturing the sync byte. A prescale setting of 8x is the desired choice for the prescaler. BRK_THRESHOLD MAX_BIT_TIME MAX_HEADER_TIME d'118' d'39' The upper boundary bit time for synchronization, which should equal ((FOSC x 1.15) / 4) /(bit rate) – 2 The maximum allowable time for the header. This value equals ((34 + 1) x 1.4) – 10, and should not be changed unless debugging. MAX_IDLE_TIME d'195' Defines the maximum bus IDLE time; the spec defines this to be 25000 bit times. The value equals 25000 / 128. The 128 comes from the LIN_IDLE_TIME_PS definition. MAX_TIME_OUT d'128' Specifies the maximum time out between wake-up requests. The LIN specification defines this to be 128 bit times. MIN_BIT_TIME d'87' NOM_BIT_TIME d'102' RC_OSC N/A The lower boundary bit time for synchronization, which should equal ((FOSC x 0.85) / 4) /(bit rate) – 2 The nominal bit time for synchronization, which should equal (FOSC / 4) /(bit rate) – 2 Enables synchronization. Do not use this definition if using a crystal or resonator. RX_ADVANCE 0x10 This is the receive advance. Use this definition to adjust center sampling for high bit rates, 7400 bps or greater at 4 MHz. RX_ADVANCE must not be used in conjunction with RX_DELAY. RX_DELAY 0xF0 The receive delay. Use this definition to adjust center sampling for low bit rates, less than 7400 bps at 4 MHz. For lower bit rates, the delay should be longer. Note, this value is complimented (i.e., 0xF0 is a delay of 16 cycles). RX_DELAY must not be used in conjunction with RX_ADVANCE. IO_MASK_A b'10111111' Logical AND mask of the transmit pin. IO_MASK_O b'01000000' Logical OR mask of the I/O pin. RX_PIN PORTC,7 The receive pin. RX_PIN_DIR TRISC,7 The receive pin direction control. TX_PIN PORTC,6 The transmit pin. TX_PIN_DIR TRISC,6 The transmit pin direction control. TX_PORT USE_GP_CHANGE DS00239A-page 18 PORTC N/A The transmit pin port. Use this definition to configure the external interrupt to be a GPIO interrupt-on-change. The alternative is to use the INT pin. 2002 Microchip Technology Inc. AN239 APPENDIX B: SOURCE CODE Due to size considerations, the complete source code for this application note is not included in the text. A complete version of the source code, with all required support files, is available for download as a Zip archive from the Microchip web site, at: www.microchip.com 2002 Microchip Technology Inc. DS00239A-page 19 AN239 NOTES: DS00239A-page 20 2002 Microchip Technology Inc. Note the following details of the code protection feature on Microchip devices: • Microchip products meet the specification contained in their particular Microchip Data Sheet. • Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions. • There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip's Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property. • Microchip is willing to work with the customer who is concerned about the integrity of their code. • Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.” Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our products. Information contained in this publication regarding device applications and the like is intended through suggestion only and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. No representation or warranty is given and no liability is assumed by Microchip Technology Incorporated with respect to the accuracy or use of such information, or infringement of patents or other intellectual property rights arising from such use or otherwise. Use of Microchip’s products as critical components in life support systems is not authorized except with express written approval by Microchip. No licenses are conveyed, implicitly or otherwise, under any intellectual property rights. Trademarks The Microchip name and logo, the Microchip logo, KEELOQ, MPLAB, PIC, PICmicro, PICSTART and PRO MATE are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. FilterLab, microID, MXDEV, MXLAB, PICMASTER, SEEVAL and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. dsPIC, dsPICDEM.net, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, microPort, Migratable Memory, MPASM, MPLIB, MPLINK, MPSIM, PICC, PICDEM, PICDEM.net, rfPIC, Select Mode and Total Endurance are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. Serialized Quick Turn Programming (SQTP) is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies. © 2002, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved. Printed on recycled paper. Microchip received QS-9000 quality system certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona in July 1999 and Mountain View, California in March 2002. The Company’s quality system processes and procedures are QS-9000 compliant for its PICmicro® 8-bit MCUs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, non-volatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001 certified. 2002 Microchip Technology Inc. DS00239A - page 21 WORLDWIDE SALES AND SERVICE AMERICAS ASIA/PACIFIC Corporate Office Australia 2355 West Chandler Blvd. Chandler, AZ 85224-6199 Tel: 480-792-7200 Fax: 480-792-7277 Technical Support: 480-792-7627 Web Address: http://www.microchip.com Microchip Technology Australia Pty Ltd Suite 22, 41 Rawson Street Epping 2121, NSW Australia Tel: 61-2-9868-6733 Fax: 61-2-9868-6755 Rocky Mountain China - Beijing 2355 West Chandler Blvd. Chandler, AZ 85224-6199 Tel: 480-792-7966 Fax: 480-792-4338 Atlanta 500 Sugar Mill Road, Suite 200B Atlanta, GA 30350 Tel: 770-640-0034 Fax: 770-640-0307 Boston 2 Lan Drive, Suite 120 Westford, MA 01886 Tel: 978-692-3848 Fax: 978-692-3821 Chicago 333 Pierce Road, Suite 180 Itasca, IL 60143 Tel: 630-285-0071 Fax: 630-285-0075 Dallas 4570 Westgrove Drive, Suite 160 Addison, TX 75001 Tel: 972-818-7423 Fax: 972-818-2924 Detroit Tri-Atria Office Building 32255 Northwestern Highway, Suite 190 Farmington Hills, MI 48334 Tel: 248-538-2250 Fax: 248-538-2260 Kokomo 2767 S. Albright Road Kokomo, Indiana 46902 Tel: 765-864-8360 Fax: 765-864-8387 Los Angeles 18201 Von Karman, Suite 1090 Irvine, CA 92612 Tel: 949-263-1888 Fax: 949-263-1338 San Jose Microchip Technology Inc. 2107 North First Street, Suite 590 San Jose, CA 95131 Tel: 408-436-7950 Fax: 408-436-7955 Toronto 6285 Northam Drive, Suite 108 Mississauga, Ontario L4V 1X5, Canada Tel: 905-673-0699 Fax: 905-673-6509 Microchip Technology Consulting (Shanghai) Co., Ltd., Beijing Liaison Office Unit 915 Bei Hai Wan Tai Bldg. No. 6 Chaoyangmen Beidajie Beijing, 100027, No. China Tel: 86-10-85282100 Fax: 86-10-85282104 China - Chengdu Microchip Technology Consulting (Shanghai) Co., Ltd., Chengdu Liaison Office Rm. 2401, 24th Floor, Ming Xing Financial Tower No. 88 TIDU Street Chengdu 610016, China Tel: 86-28-86766200 Fax: 86-28-86766599 China - Fuzhou Microchip Technology Consulting (Shanghai) Co., Ltd., Fuzhou Liaison Office Unit 28F, World Trade Plaza No. 71 Wusi Road Fuzhou 350001, China Tel: 86-591-7503506 Fax: 86-591-7503521 China - Shanghai Microchip Technology Consulting (Shanghai) Co., Ltd. Room 701, Bldg. B Far East International Plaza No. 317 Xian Xia Road Shanghai, 200051 Tel: 86-21-6275-5700 Fax: 86-21-6275-5060 China - Shenzhen Microchip Technology Consulting (Shanghai) Co., Ltd., Shenzhen Liaison Office Rm. 1315, 13/F, Shenzhen Kerry Centre, Renminnan Lu Shenzhen 518001, China Tel: 86-755-82350361 Fax: 86-755-82366086 China - Hong Kong SAR Microchip Technology Hongkong Ltd. Unit 901-6, Tower 2, Metroplaza 223 Hing Fong Road Kwai Fong, N.T., Hong Kong Tel: 852-2401-1200 Fax: 852-2401-3431 India Microchip Technology Inc. India Liaison Office Divyasree Chambers 1 Floor, Wing A (A3/A4) No. 11, O’Shaugnessey Road Bangalore, 560 025, India Tel: 91-80-2290061 Fax: 91-80-2290062 Japan Microchip Technology Japan K.K. Benex S-1 6F 3-18-20, Shinyokohama Kohoku-Ku, Yokohama-shi Kanagawa, 222-0033, Japan Tel: 81-45-471- 6166 Fax: 81-45-471-6122 Korea Microchip Technology Korea 168-1, Youngbo Bldg. 3 Floor Samsung-Dong, Kangnam-Ku Seoul, Korea 135-882 Tel: 82-2-554-7200 Fax: 82-2-558-5934 Singapore Microchip Technology Singapore Pte Ltd. 200 Middle Road #07-02 Prime Centre Singapore, 188980 Tel: 65-6334-8870 Fax: 65-6334-8850 Taiwan Microchip Technology (Barbados) Inc., Taiwan Branch 11F-3, No. 207 Tung Hua North Road Taipei, 105, Taiwan Tel: 886-2-2717-7175 Fax: 886-2-2545-0139 EUROPE Austria Microchip Technology Austria GmbH Durisolstrasse 2 A-4600 Wels Austria Tel: 43-7242-2244-399 Fax: 43-7242-2244-393 Denmark Microchip Technology Nordic ApS Regus Business Centre Lautrup hoj 1-3 Ballerup DK-2750 Denmark Tel: 45 4420 9895 Fax: 45 4420 9910 France Microchip Technology SARL Parc d’Activite du Moulin de Massy 43 Rue du Saule Trapu Batiment A - ler Etage 91300 Massy, France Tel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79 Germany Microchip Technology GmbH Steinheilstrasse 10 D-85737 Ismaning, Germany Tel: 49-89-627-144 0 Fax: 49-89-627-144-44 Italy Microchip Technology SRL Centro Direzionale Colleoni Palazzo Taurus 1 V. Le Colleoni 1 20041 Agrate Brianza Milan, Italy Tel: 39-039-65791-1 Fax: 39-039-6899883 United Kingdom Microchip Ltd. 505 Eskdale Road Winnersh Triangle Wokingham Berkshire, England RG41 5TU Tel: 44 118 921 5869 Fax: 44-118 921-5820 10/18/02 DS00239A-page 22 2002 Microchip Technology Inc.