an237 - implementing a lin slave node using eusart on a 8-bit...

20
2002-2015 Microchip Technology Inc. DS00000237B-page 1 AN237 INTRODUCTION This application note presents a LIN 2.0 slave driver for an 8-bit PIC ® microcontroller with on-chip Enhanced Universal Synchronous Receiver Transmitter (EUSART) peripheral. EUSART is a USART with added features like automatic detection and calibration of the baud rate, wake-up on Break reception and 13- bit Break character transmit to support LIN applications. This document also shows cases how MPLAB ® Code Configurator (MCC) can be used in developing the LIN drivers. This application note focuses mainly on how to setup MCC and use the drivers generated by MCC, so the LIN system designer is able to get an application running on LIN quickly. In this application note, the PIC16F1783 is used, but any 8-bit PIC microcontroller with EUSART can be used. The information in this application note is presented with the assumption that the reader is familiar with LIN specification v2.0. Therefore, not all details about LIN are discussed. Refer to the References section of this document for additional information. LIN PROTOCOL LIN (Local Interconnect Network) provides a low-cost bus communication for many networks, including automotive and appliance. LIN protocol provides system development guidelines for data communication. The key features of the LIN are: Low-cost, single-wire implementation Single master, multiple slaves – up to 16 Slaves capable of synchronizing to any baud rate from 2K to 20K. Self-synchronization of slaves to master’s speed Data format similar to common serial UART format Data checksums and bit-error detection for reliable operation. LIN 2.0 Compatibility with LIN 1.x The LIN 2.0 specification is a superset of LIN 1.x. Nodes designed to the LIN 2.0 specification and the LIN 1.x specification will communicate with each other with a few exceptions. The LIN 2.0 master node cannot request the new LIN 2.0 features from a LIN 1.x node: Enhanced checksum Reconfiguration and diagnostics Automatic baud rate detection Response error status monitoring A LIN 2.0 slave node will not work with a LIN 1.x master unless the slave node is reconfigured. APPLICATIONS The first question that should 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 or device for their application. The important elements that have significant weight on this decision include available process time, resource usage, and bit rate performance. Process Time The process time is dictated predominately by bit rate, clock frequency, and code execution. This is why the EUSART module is recommended for LIN communication. This hardware resource puts more processing in hardware and less demand for firmware. Thus, the average Firmware Process Time is relatively low. Table 1 shows the approximate average Firmware Process Time for FOSC equal to 16 MHz. Author: Dinesh Baria Microchip Technology Inc. TABLE 1: FIRMWARE PROCESS TIME Bit Rate (bps) Firmware Process Time (%) 2000 2.7 2400 3.2 9600 13 10417 14 20000 27 Implementing a LIN Slave Node using EUSART on a 8-Bit PIC ® Microcontroller

Upload: others

Post on 06-Jul-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

AN237Implementing a LIN Slave Node using EUSART on a 8-Bit

PIC® Microcontroller

INTRODUCTION

This application note presents a LIN 2.0 slave driver foran 8-bit PIC® microcontroller with on-chip EnhancedUniversal Synchronous Receiver Transmitter(EUSART) peripheral. EUSART is a USART withadded features like automatic detection and calibrationof the baud rate, wake-up on Break reception and 13-bit Break character transmit to support LINapplications. This document also shows cases howMPLAB® Code Configurator (MCC) can be used indeveloping the LIN drivers. This application notefocuses mainly on how to setup MCC and use thedrivers generated by MCC, so the LIN system designeris able to get an application running on LIN quickly. Inthis application note, the PIC16F1783 is used, but any8-bit PIC microcontroller with EUSART can be used.

The information in this application note is presentedwith the assumption that the reader is familiar with LINspecification v2.0. Therefore, not all details about LINare discussed. Refer to the References section of thisdocument for additional information.

LIN PROTOCOL

LIN (Local Interconnect Network) provides a low-costbus communication for many networks, includingautomotive and appliance. LIN protocol providessystem development guidelines for datacommunication. The key features of the LIN are:

• Low-cost, single-wire implementation

• Single master, multiple slaves – up to 16

• Slaves capable of synchronizing to any baud rate from 2K to 20K.

• Self-synchronization of slaves to master’s speed

• Data format similar to common serial UART format

• Data checksums and bit-error detection for reliable operation.

LIN 2.0 Compatibility with LIN 1.x

The LIN 2.0 specification is a superset of LIN 1.x.Nodes designed to the LIN 2.0 specification and theLIN 1.x specification will communicate with each otherwith a few exceptions. The LIN 2.0 master node cannotrequest the new LIN 2.0 features from a LIN 1.x node:

• Enhanced checksum

• Reconfiguration and diagnostics

• Automatic baud rate detection

• Response error status monitoring

A LIN 2.0 slave node will not work with a LIN 1.x masterunless the slave node is reconfigured.

APPLICATIONS

The first question that should be asked is: “Will thisdriver work for my application?” The next few sectionscan help those who would like to know the answer tothis question and quickly decide whether this is theappropriate driver implementation or device for theirapplication. The important elements that havesignificant weight on this decision include availableprocess time, resource usage, and bit rateperformance.

Process Time

The process time is dictated predominately by bit rate,clock frequency, and code execution. This is why theEUSART module is recommended for LINcommunication. This hardware resource puts moreprocessing in hardware and less demand for firmware.Thus, the average Firmware Process Time is relativelylow. Table 1 shows the approximate average FirmwareProcess Time for FOSC equal to 16 MHz.

Author: Dinesh BariaMicrochip Technology Inc.

TABLE 1: FIRMWARE PROCESS TIME

Bit Rate (bps) Firmware Process Time (%)

2000 2.7

2400 3.2

9600 13

10417 14

20000 27

2002-2015 Microchip Technology Inc. DS00000237B-page 1

Page 2: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

When the LIN bus is IDLE, the driver uses even lessprocess time, approximately 1% at 16 MHz.

Resource Usage

The resource required on the PIC16F1783 (or anyother devices which have EUSART module) are:

• EUSART – used for communication

• Timer1 – used for bus and frame timing

• Program Memory – 885 Words for Firmware LIN Drivers

• Data Memory – 22 Bytes

Bit Rate

The driver is designed to achieve the maximum bit ratedefined by the LIN specification: 20000 bps. To ensureproper detection of Break and Sync, the internal clockneeds to be accurate and synchronized. The clock fre-quency is defined by the master. All slaves synchronizetheir internal clock during the sync field inside theheader. For the complete LIN-frame (header plusresponse) the allowed clock deviation is < ±2%,according to the LIN specification.

Summary

The LIN Slave driver takes advantage of the EUSARTmodule to handle most of the otherwise demandingprocessing, so process time is of little concern. Timer1is the only other resource, and it interrupts at the bitrate. Therefore, the driver can run virtually transparentin the background without significant interference to theapplication.

Since most of the resources, including process time,are available, this driver is well suited for high demand,high-process time applications.

SETTING UP THE DRIVER

To set up the firmware and start building an application,the user can configure and generate the module driversfor EUSART and Timer1 using the MLPAB CodeConfigurator. The user needs to include the LIN driverfiles, provided in the appendix, into their project.

Prior to setting up the driver, the MPLAB X IDE, XC8compiler, and MPLAB Code Configurator (MCC) plug-in must be installed. Here are the basic steps requiredto set up your project:

1. Create a new MPLAB X IDE project or open anexisting project.

2. Open the MCC plug-in tool. For this, in the menubar of MPLAB X IDE, go to Tools-> Embeddedand click MPLAB Code Configurator.

3. Clicking the System module in the ProjectResources area invokes the Configuration bitssetting GUI in the Composer area where deviceConfiguration bits can be set. Also enter thesystem frequency if EC/HS/XT oscillator isused. Refer to Figure 1 and look at the encircleditems.

4. From the Device Resources area, select Timer1and EUSART asynchronous (NRZ) modules.When double clicking on these modules, themodules appear on the Project Resources area.Any other modules that are used in theapplication can also be moved into the ProjectResource area.

5. In the Project Resource area, select EUSARTasynchronous (NRZ) module and configure it asshown in Figure 2. Some microcontrollers (e.g.,PIC16F1708) include a feature called PeripheralPin Select (PPS) that allows the programmer toassign many of the peripherals offered by themicrocontroller to any pins. The programmerhas to lock the GPIO pins in the pin managerwindow to configure the GPIO pins as EUSARTTX and RX pins.

6. In the Project Resource area, select Timer1module and configure it as shown in Figure 3.The timer period value is equal to the bit ratevalue required for LIN communication. Thefollowing equation gives the bit time based onEUSART baud rate for Timer1.

T = 0xFFFF – (BRG+1) /PR

The value T represents the 16-bit value loaded inthe TMR1 register. The value BRG represents the16-bit value of the baud rate timer (SPBRGH:SPBRGL). The value PR represents the Timer1prescaler value.

DS00000237B-page 2 2002-2015 Microchip Technology Inc.

Page 3: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

FIGURE 1: SYSTEM MODULE GUI

FIGURE 2: EUSART ASYNCHRONOUS (NRZ) CONFIGURATION GUI

2002-2015 Microchip Technology Inc. DS00000237B-page 3

Page 4: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

FIGURE 3: TIMER1 CONFIGURATION GUI

7. Also configure the other modules that aremoved into the Project Resource area.

8. In the Project Resource area, select theInterrupt Manager module and change theinterrupt priority as per the applicationrequirements, as can be seen in Figure 4.

9. When all the modules configurations are done,click on the Generate Code button at the top ofthe Composer area to generate the drives andinitializers. Generated drivers will be included inthe active MPLAB X IDE project (see Figure 5).

10. Add the LIN driver files to your project: lin.c,lin.h, lin_app.c, and lin_app.h. Thesefiles are available in an example project.

FIGURE 4: INTERRUPT MANAGER GUI

DS00000237B-page 4 2002-2015 Microchip Technology Inc.

Page 5: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

FIGURE 5: PROJECT WINDOW

11. The mcc.h and mcc.c files include the defini-tions of Configuration bits and theoscillator_initializer. It also includesthe system_initializer function whichneeds to be called in the application programthat internally calls other required initializers likeEUSART initializer and Timer1 initializer.

12. The pin_manager.h and pin_manager.cfiles include the pin manager initializer functionsbased on the configurations which were made inthe pin manager GUI.

13. The interrupt_manager.h andinterrupt_manager.c files include interruptinitializer and Interrupt Service Routines.

14. The tmr1.h and tmr1.c files include Timer1configuration functions.

15. The eusart.h and eusart.c files includeEUSART configuration functions.

16. The lin.h and lin.c files include LIN configurationfunctions. The lin.h contains the definition ofnew types and the prototypes of the functionsdefined in lin.c.

17. The lin_app.h and lin_app.c files are theapplication interface and should be filled by theuser. Edit these files to respond to theappropriate IDs. This could be a table or somesimple compare logic. In this way, the user candefine the LIN communication of his application.

2002-2015 Microchip Technology Inc. DS00000237B-page 5

Page 6: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

18. Add any additional application related files. Theexample uses lin_xxxevent.c for applica-tion related functions related to specific IDs.

19. The main.c file contains the entry point inprogram. Edit this file as required for theapplication. Make sure that the interrupt is setupcorrectly, and initialize the driver. Also, ensureany external symbols are included. Forreference, a complete application provided inthe appendix, is built to with the LIN driver.

The Project

The first step is to setup the project in MPLAB X IDE.Figure 5 shows an example of how the project setuplooks like. The following files are required for the LINdriver to operate:

• lin.c – the driver file

• lin.h – the header file for the driver configura-tion

• lin_app.h – the node configuration file

• lin_app.c – the LIN event handling file

Any additional files are defined by the system designerfor the specific application. For example, Figure 5 liststhese project files as lin_xxxevent.c, where xxxrepresents the LIN ID event name. This is simply aprogramming style that separates ID handling intoindividual objects, thus making the project formateasier to understand.

The Main Object

The main.c module contains the entry point into theprogram, which is where the driver, hardware, andvariables should be initialized. To initialize the LINdriver, call the LIN_Initializer function.

Within the main function, the driver function,LIN_Driver, should be called as shown inExample 1. Within the function, read the receive bufferand process the data.

EXAMPLE 1: MAIN ENTRY POINT

Modify the EUSART_Receive_ISR () function whichis in eusart.c, as shown in Example 2 to enable autobaud feature.

EXAMPLE 2: EUSART RX ISR

In eusart.h, add the following macros to enable theauto wake-up feature and read the STATUS register.

#define EUSART_Status( ) (RC1STA)

#define EUSART_EnableAutoWakeUp( )

(BAUD1CONbits.WUE = 1)

#define EUSART_HasBreakDetected( )

(! (BAUD1CON & 0x02))

The timekeeper function is also placed in the‘TMR1_ISR ()’ function, which is in the tmr1.c file.The example firmware uses Timer1 for bus time out;however, the LIN designer can choose any timer.Example 3 shows the placement within the interrupt.

EXAMPLE 3: TMR1 ISR

void main(void){ //System Initialization //LIN Driver Initialization LIN_Initializer( ); while(1) { //Check Data Received

if(EUSART_DataReady){ LIN_Driver( );}//Add application code here

}

}

void EUSART_Receive_ISR(void) { //overrun check code // LIN Implementation

if(!EUSART_HasBreakDetected()) { while(!EUSART_HasBreakDetected()); BAUD1CONbits.ABDEN = 1; } //read buffer code

}

Void TMR1_ISR(void){ //Clear the TMR1 interrupt flag PIR1bits.TMR1IF = 0; TMR1 += timer1ReloadVal;

//Add your TMR1 interrupt custom code LIN_UpdateTimer( );

}

DS00000237B-page 6 2002-2015 Microchip Technology Inc.

Page 7: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

Definitions

There are a few compile time definitions, all of themlocated in lin.h, that are used to setup the system.Table 2 lists and describes these definitions.

LIN Events

LIN event functions are where the ID is decoded todetermine the next action: what to transmit, what is thedevice expected to receive, and how may bytes totransmit/receive. The designer should edit or modifythe event function to handle specific LIN IDs. Onepossibility is to set up an ID table, which is useful forapplications that require responding to multiple IDs.Another option is to setup some simple compare logic.The example code provided in appendix is based oncompare logic.

ID Modules

The example firmware uses separate ID files forindividual handling of IDs and their associatedfunctions. The most important part to remember is toinclude all of the external symbols that are used. Thesymbols used by the driver are in lin_app.h, whichshould be included in every application module.

The function in lin_app.c is used to setup the driverto handle the ID event. The user can add this functionto handle additional ID event.

USING THE DRIVER

After setting up a project with the LIN driver’snecessary files, it is time to start using the driver. Thissection presents information about using the driver.The important information addressed is:

• Handling communication flags

• Handling error flags

• State flags within the driver

• LIN ID events

• Bus wake-up

The source code provided is a simple example onusing the LIN driver in an application.

Communication Flags

There are two flags that indicate when the driver hassuccessfully completed transmission or reception ofdata. The complete flag is set when data has beentransmitted or received without error. This flag must becleared by the user after it is handled. Likewise, thepending flag indicates the transmit or receive operationis going on. The pending flag must also be cleared bythe user after it is handled.

Error Flags

Certain error flags are set when expected conditionsare not met. For example, if the slave failed to matchreceived PID with calculated PID, a parity error flag willget set in the driver. Errors are considered fatal untilthey are handled and cleared. Thus, if the error is nevercleared, then the driver will ignore incoming data.

The following code, shown in Example 4,demonstrates how to handle errors within the mainprogram loop. This example only shows a response toa bus time-out error. This same concept can be appliedto other types of errors.

EXAMPLE 4: ERROR HANDLING

TABLE 2: COMPILE TIME DEFINITIONS

Definition Name Value Description

MAX_IDLE_TIME 25000 This value is the maximum IDLE bus time. The LIN specification defines this to be 25000.

MAX_HEADER_TIME 39 This value is the maximum allowable header time. The specification defines this to be 49; however, timing does not start until after the first byte (break), so it is actually 39 (10 less than the definition).

MAX_TIME_OUT 128 This is the maximum time allowed to wait after the wake-up request has been made.

void main(void){ //System Initialization //LIN Driver Initialization LIN_Initializer( ); while(1) { //Check Data Received

if(EUSART_DataReady){ LIN_Driver( );}//Check Bus Timeout errorif(l_errflgs_b.bits.LE_TIMEOUT==1){

LIN GotoSleep();

2002-2015 Microchip Technology Inc. DS00000237B-page 7

Page 8: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

Driver States

The LIN driver uses different states to remember whereit is between received bytes. After a byte is received,the driver uses these states to decide what the nextunexecuted state is, then change to that state.

ID Events and Functions

For each ID there exists an event function. The eventfunction is required to tell the driver how to respond tothe data following the ID. For example, the driver needsto prepare to receive or transmit data. Also, how muchdata is expected to be received or transmitted.

For successful operation, three variables must beinitialized:

• A pointer to data memory

• Frame time

• Data length

Waking the Bus

A LIN bus wake-up function, LIN_SendWakeupSig-nal, is provided for applications that need the ability towake the bus up. Calling this function will broadcast thewake-up request character.

IMPLEMENTATION

There are four functions found in the associatedexample firmware that control the operation of the LINinterface:

• LIN Transmit/Receive Driver

• LIN Timekeeper

• LIN Initialization

• LIN Wake-up

The Driver

The Enhanced USART module is the key element usedfor LIN communications. Using the EUSART module asthe serial engine for LIN has certain advantages. Oneparticular advantage is that it puts serial control in thehardware, rather than in the software. Thus,miscellaneous processing can be performed while datais being transmitted or received. According to this, theSlave Node LIN Protocol Driver is designed to run inthe background, basically as a daemon.

The driver is interrupt driven via the EUSART receiveinterrupt. Because of the physical feedback nature ofthe LIN bus (Figure 6), a EUSART receive interrupt willoccur regardless of transmit or receive operation. Inaddition, errors flags are maintained to indicate errorsduring transmit or receive operations.

FIGURE 6: SIMPLIFIED LIN TRANSCEIVER

DS00000237B-page 8 2002-2015 Microchip Technology Inc.

Page 9: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

STATES AND STATE FLAGS

The LIN driver uses state flags to indicate current stateof the LIN transceiver. When an interrupt occurs, thedriver uses these flags to decide what the next

unexecuted state is, and then jumps to that state.Figure 7 and Figure 8 outline the program flow throughthe different states. Table 4 lists and describes thestates definitions.

FIGURE 7: RECEIVER HEADER PROGRAM FLOW

2002-2015 Microchip Technology Inc. DS00000237B-page 9

Page 10: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

FIGURE 8: TRANSMIT/RECEIVE MESSAGE PROGRAM FLOW

DS00000237B-page 10 2002-2015 Microchip Technology Inc.

Page 11: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

Time-out Implementation

The time-out feature is user-selectable and dependentof the baud rate chosen by the user. If enabled,Timer1 is used to track the calculated maximumresponse time allowed. The LIN specification 2.0describes the frame slot time allocation requirementsas the following:• The nominal value for transmission of a frame

matches the number of bits transmitted excluding any response space, byte spaces or inter-frame space.

THeader_Nominal = 34 * TBit

TResponse_Nominal = 10*(NData+1)*TBit

TFrame_Nominal = THeader_Nominal +TResponse_Nominal

The maximum value between the bytes is an additional40% of time allowance compared to the nominal value.

THeader_Maximum = 1.4 * THeader_Nominal

TResponse_Maximum = 1.4* TResponse_Nominal

TFrame_Maximum = THeader_Maximum +TResponse_Maximum

- TBit is the time required to transmit one bit

- NData is the number of data bytes in the frame

When using time out, the timing starts with the maxheader time calculation that begins after receiving thefirst 10 TBits of the Sync Break. After the Sync Break isverified by checking for 0x00 in the receiver buffer andthe frame error flag bit, Timer1 is enabled and writtenwith the value of (THeader_Maximum - 10*TBit). Theheader time-out count ends after the identifier has beenreceived or a time-out event. The identifier providesinformation about the length of the response. Thereforeresponse time-out value can be calculated by first mul-tiplying the total number of bytes (data plus one byte ofchecksum) and TBit then add the remaining time leftthat was not used from the header time out. Figure 9shows the flow of timekeeping function.

FIGURE 9: TIMEKEEPING PROGRAM FLOW

2002-2015 Microchip Technology Inc. DS00000237B-page 11

Page 12: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

LIN Slave Driver File Description

lin.h

The lin.h contains the definition of new types and theprototypes of the functions defined in lin.c.

TABLE 3: VARIABLES

Variable Name Bytes Description

readback_b 1 Holding the transmitted data to be compared with received data for bit error detection

chksum_w 2 Used by the driver to calculate checksum for transmit and receive

datalength_b 1 Used by the driver to maintain a message data count

handle_b 1 Holding register for the received identifier byte

bufferptr_b 1 Pointer to a storage area used by the driver. Data is either loaded into or read from memory depending on the identifier

l_state_b 1 Indicate what state the LIN bus is in

l_errflgs_b 1 Contains the error information about the LIN bus

l_comflgs_b 1 Indicate the current bus activity

TABLE 4: LIN STATES

Enum. Value

State Name Description

0 LIN_ST_SYNCHBREAK In this state slave ready to receive break field

1 LIN_ST_SYNCHBYTE In this state slave receives the sync byte

2 LIN_ST_IDENTIFIER In this state slave receives the protected ID

3 LIN_ST_XMIT In this state slave responds to the master request

4 LIN_ST_RECEIVE In this state slave receives the data from master

5 LIN_ST_SLEEP In this state slave ready to receive wake-up signal

DS00000237B-page 12 2002-2015 Microchip Technology Inc.

Page 13: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

REGISTER 1: ERROR FLAGS

R/W-0/0 R/W-0/0 R/W-0/0 R/W-0/0 R/W-0/0 R/W-0/0 R/W-0/0 R/W-0/0

LE_TIMEOUT LE_NORESPONSE LE_INCOMPLETE LE_BITERR LE_CHKSUMERR LE_PARITYERR LE_SYNCERR LE_BRKERR

7 0

Legend:

R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’

-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown

bit 7 LE_TIMEOUT: Time-Out Error bit1 = Bus activity time-out error occurred0 = No bus activity time-out error occurred

bit 6 LE_NORESPONSE: No Response Error bit1 = No response from the master during a Receive mode0 = Response from the master during a Receive mode

bit 5 LE_INCOMPLETE: Incomplete Error bit1 = Incomplete transmission or reception of frame occurred0 = Complete transmission or reception of frame occurred

bit 4 LE_BITTERR: Bit Error bit1 = Bit error occurred during communication0 = No bit error occurred during communication

bit 3 LE_CHKSUMERR: Checksum Error bit1 = Checksum error occurred during a Receive mode0 = No checksum error occurred during a Receive mode

bit 2 LE_PARITYERR: Parity Error bit1 = Parity error occurred in received PID0 = No parity error occurred in received PID

bit 1 LE_SYNCERR: Synchronization Error bit1 = Sync field is not detected0 = Sync field is detected

bit 0 LE_BRKERR: Break Error bit1 = Break field is not detected0 = Break field is detected

2002-2015 Microchip Technology Inc. DS00000237B-page 13

Page 14: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

REGISTER 2: STATUS FLAGS

R-W/0-0

LastFrame_PID<7:0>

bit 15 bit 8

U-0 U-0 U-0 U-0 U-0 R-W/0-0 R-W/0-0 R-W/0-0 R-W/0-0

— — — — — Goto_sleep Overrun Successful_transfer Error_In_Response

bit 7 bit 0

Legend:

R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’

-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown

bit 15-8 LastFrame_PID<7:0>: Last Frame Protected IdentityLast frame protected identity is the protected identity last detected on the bus and processed in the node. If overrun is set one or more values of last frame protected identity are lost; only the latest vale is maintained.

bit 7-4 Reserved

bit 3 Goto_Sleep: Go to Sleep Flag bit1 = A GOTO Sleep command has been received since the previous call to read status function0 = A GOTO Sleep command has not been received

bit 2 Overrun: Overrun Flag bit1 = Two or more frames are processed since the last call to read status function0 = No overrun occurred

bit 1 Successful_transfer: Successful Transfer Flag bit1 = One (or multiple) frame responses has been processed without an error since the last call to read status function0 = Frame transfer is not completed

bit 0 Err_In_Response: Error in Response Fag bit1 = One (or multiple) frames processed by the node had an error in the frame response section (e.g., checksum error, framing error, etc.), since the previous call to read status function0 = No frame response error

DS00000237B-page 14 2002-2015 Microchip Technology Inc.

Page 15: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

lin.c

The lin.c file has all the functions required for theoperation of the LIN slave. This section describes eachAPI function and includes comments about how to usethe function.

• LIN_Initializer- C Prototype: void LIN_Initializer (void)

- Description: Initializes all the required parameters of LIN slave. Call this function in the main function after the system initialization to start the LIN operation.

- Parameters: None

- Returns: None

• LIN_Driver- C Prototype: void LIN_Driver (void);

- Description: This function receives the LIN signals and changes the state according the current LIN signals.

- Parameters: None

- Returns: None

• LIN_ReadStatus- C Prototype: lin_status LIN_ReadSta-tus(void);

- Description: The call returns a 16-bit status word.

- Parameters: None.

- Returns: 16-bit status word

• LIN_SendWakeupSignal- C Prototype: void LIN_SendWakeupSig-nal (void);

- Description: Generates a wake-up command on the bus. This function sends a wake-up character on the LIN bus, which will simulate a wake-up call.

- Parameters: None.

- Returns: None

• LIN_GotoSleep- C Prototype: void LIN_GotoSleep (void);

- Description: Sets the Goto_sleep flag bit, disables the timer and goes into the Sleep mode. Use this function when master sends the GOTO SLEEP command.

- Parameters: None

- Returns: None

REGISTER 3: COMMUNICATION FLAGS

U-0 U-0 U-0 U-0 U-0 U-0 R/W-0/0 R/W-0/0

— — — — — — LF_COMPLETE LF_PENDING

bit 7 bit 0

Legend:

R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’

-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared

bit 7-2 Reserved

bit 1 LF_COMPLETE: Communication Complete Flag bit1 = A transmission or reception has been completed0 = A transmission or reception has not been completed

bit 0 LF_PENDING: Communication Pending Flag bit1 = A transmission or reception is going on0 = A transmission or reception is not yet started

2002-2015 Microchip Technology Inc. DS00000237B-page 15

Page 16: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

• LIN_AssignFrameID- C Prototype: uint8_t LIN_AssignFra-meID (uint8_t *l_NAD)

- Description: This function assigns the protected identifier of a frame in the slave node with the address NAD and the specified supplier ID. The frame changed shall have specified message ID and will after the call have PID as the protected identifier.

- Parameters: None

- Returns: 8-bit Value

• LIN_AssignNAD- C Prototype: uint8_t LIN_AssignNAD

(uint8_t *l_NAD)

- Description: This function assigns the NAD (node diagnostic address) of all slave nodes

that matches the NAD, the supplier identity code and the function identity code. The new NAD of those nodes will be new NAD.

- Parameters: None

- Returns: 8-bit Value

• LIN_ReadByID- C Prototype: uint8_t LIN_ReadByID

(uint8_t *l_NAD)

- Description: This function requests the node selected with the NAD to return the property associated with the ID parameter. Refer to Table 5.

- Parameters: None

- Returns: 8 bit Value

lin_app.h

This file is an extract of the LIN Description File (LDF)that represents the node configuration.

The file is structured as follows:

• Frame Definition

• Frame Union Definition

• Reserved buffer size for data exchange

Frame Definition

• #define <Frame_Name>_Index value

Defines the Index value. Value is a user-definedincremental integer.

• #define <Frame_Name>_ID value

Defines the frame identifier; value is in the range of 0 to63(0x3F)

• #define <Frame_Name>_PID value

Defines the protected frame identifier. See Appendix7.2, located in “LIN Specification Package Revision2.0” [1].

• #define <Frame_Name>_Len value

Defines the response frame length without thechecksum.

• #define <Frame_Name>_MsgID value

Defines Message identifier for the each event of theslave node.

lin_app.h

This file is the application interface and should be filledby the user. In this way, the user can define the LINcommunication of his application.

The lin_app.c file consists of:

The ID_Table variable

You fill this variable to define the identifiers of the LINframes that the application has to handle.

TABLE 5: POSSIBLE VALUES FOR ID

ID Interpretation

0 LIN Product Identification

1 Serial Number

2 – 15 Reserved

16 – 31 Message ID 1…16

32 – 63 User defined

64 – 255 Reserved

DS00000237B-page 16 2002-2015 Microchip Technology Inc.

Page 17: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

Each member of this list corresponds to a LIN frameand its corresponding identifier. Each member is oftype t_id_list and has to be defined in the followingway:

EXAMPLE 5: ID LIST

• bufferptr represents the address of the memory allocated to frame.

• len represents the number of data bytes of the corresponding frame. It can be set between 0 to 8.

• idptr represents the address of the variable to store the frame identifier.

• direction represents the data flow direction, is of type t_message_direction and should therefor be set to ID_REQUEST and ID_RESPONSE for data being request by the master and to sent by the slave.

• MsgID represents the message identifier of the each frame.

REFERENCES

1. “LIN Specification Package Revision 2.0”, LINConsortium, http://www.lin-subbus.org

2. “MPLAB® Code Configurator User’s Guide”,(DS40001725), http://www.microchip.com/pagehandler/en_us/devtools/code_configura-tor/home.html

3. “MPLAB® XC8 C Compiler User’sGuide”(DS50002053) Microchip Technology,Inc.

APPENDIX A: SOURCE CODE

Due to size considerations, the complete source codefor this application note is not included in the text. Acomplete version of the source code, with all requiredsupport files, is available for download as a Zip archivefrom the Microchip web site at: www.microchip.com.

typedef struct{ uint8_t *bufferptr; uint8_t len; uint8_t *idptr; t_msg_direction direction; uint16_t MsgID;

}t_id_list;

2002-2015 Microchip Technology Inc. DS00000237B-page 17

Page 18: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

NOTES:

DS00000237B-page 18 2002-2015 Microchip Technology Inc.

Page 19: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

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 ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.

Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights.

2002-2015 Microchip Technology Inc.

QUALITY MANAGEMENT SYSTEM CERTIFIED BY DNV

== ISO/TS 16949 ==

Trademarks

The Microchip name and logo, the Microchip logo, dsPIC, FlashFlex, flexPWR, JukeBlox, KEELOQ, KEELOQ logo, Kleer, LANCheck, MediaLB, MOST, MOST logo, MPLAB, OptoLyzer, PIC, PICSTART, PIC32 logo, RightTouch, SpyNIC, SST, SST Logo, SuperFlash and UNI/O are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

The Embedded Control Solutions Company and mTouch are registered trademarks of Microchip Technology Incorporated in the U.S.A.

Analog-for-the-Digital Age, BodyCom, chipKIT, chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net, ECAN, In-Circuit Serial Programming, ICSP, Inter-Chip Connectivity, KleerNet, KleerNet logo, MiWi, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, RightTouch logo, REAL ICE, SQI, Serial Quad I/O, Total Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.

Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.

GestIC is a registered trademarks of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip Technology Inc., in other countries.

All other trademarks mentioned herein are property of their respective companies.

© 2002-2015, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.

ISBN: 978-1-63276-943-5

Microchip received ISO/TS-16949:2009 certification for its worldwide

DS00000237B-page 19

headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.

Page 20: AN237 - Implementing a LIN Slave Node Using EUSART on a 8-Bit …ww1.microchip.com/downloads/en/AppNotes/00000237B.pdf · 2015-08-26 · 2002-2015 Microchip Technology Inc. DS00000237B-page

DS00000237B-page 20 2002-2015 Microchip Technology Inc.

AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://www.microchip.com/supportWeb Address: www.microchip.com

AtlantaDuluth, GA Tel: 678-957-9614 Fax: 678-957-1455

Austin, TXTel: 512-257-3370

BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088

ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075

ClevelandIndependence, OH Tel: 216-447-0464 Fax: 216-447-0643

DallasAddison, TX Tel: 972-818-7423 Fax: 972-818-2924

DetroitNovi, MI Tel: 248-848-4000

Houston, TX Tel: 281-894-5983

IndianapolisNoblesville, IN Tel: 317-773-8323Fax: 317-773-5453

Los AngelesMission Viejo, CA Tel: 949-462-9523 Fax: 949-462-9608

New York, NY Tel: 631-435-6000

San Jose, CA Tel: 408-735-9110

Canada - TorontoTel: 905-673-0699 Fax: 905-673-6509

ASIA/PACIFICAsia Pacific OfficeSuites 3707-14, 37th FloorTower 6, The GatewayHarbour City, KowloonHong KongTel: 852-2943-5100Fax: 852-2401-3431

Australia - SydneyTel: 61-2-9868-6733Fax: 61-2-9868-6755

China - BeijingTel: 86-10-8569-7000 Fax: 86-10-8528-2104

China - ChengduTel: 86-28-8665-5511Fax: 86-28-8665-7889

China - ChongqingTel: 86-23-8980-9588Fax: 86-23-8980-9500

China - HangzhouTel: 86-571-8792-8115 Fax: 86-571-8792-8116

China - Hong Kong SARTel: 852-2943-5100 Fax: 852-2401-3431

China - NanjingTel: 86-25-8473-2460Fax: 86-25-8473-2470

China - QingdaoTel: 86-532-8502-7355Fax: 86-532-8502-7205

China - ShanghaiTel: 86-21-5407-5533 Fax: 86-21-5407-5066

China - ShenyangTel: 86-24-2334-2829Fax: 86-24-2334-2393

China - ShenzhenTel: 86-755-8864-2200 Fax: 86-755-8203-1760

China - WuhanTel: 86-27-5980-5300Fax: 86-27-5980-5118

China - XianTel: 86-29-8833-7252Fax: 86-29-8833-7256

China - XiamenTel: 86-592-2388138 Fax: 86-592-2388130

China - ZhuhaiTel: 86-756-3210040 Fax: 86-756-3210049

ASIA/PACIFICIndia - BangaloreTel: 91-80-3090-4444 Fax: 91-80-3090-4123

India - New DelhiTel: 91-11-4160-8631Fax: 91-11-4160-8632

India - PuneTel: 91-20-3019-1500

Japan - OsakaTel: 81-6-6152-7160 Fax: 81-6-6152-9310

Japan - TokyoTel: 81-3-6880- 3770 Fax: 81-3-6880-3771

Korea - DaeguTel: 82-53-744-4301Fax: 82-53-744-4302

Korea - SeoulTel: 82-2-554-7200Fax: 82-2-558-5932 or 82-2-558-5934

Malaysia - Kuala LumpurTel: 60-3-6201-9857Fax: 60-3-6201-9859

Malaysia - PenangTel: 60-4-227-8870Fax: 60-4-227-4068

Philippines - ManilaTel: 63-2-634-9065Fax: 63-2-634-9069

SingaporeTel: 65-6334-8870Fax: 65-6334-8850

Taiwan - Hsin ChuTel: 886-3-5778-366Fax: 886-3-5770-955

Taiwan - KaohsiungTel: 886-7-213-7830

Taiwan - TaipeiTel: 886-2-2508-8600 Fax: 886-2-2508-0102

Thailand - BangkokTel: 66-2-694-1351Fax: 66-2-694-1350

EUROPEAustria - WelsTel: 43-7242-2244-39Fax: 43-7242-2244-393Denmark - CopenhagenTel: 45-4450-2828 Fax: 45-4485-2829

France - ParisTel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79

Germany - DusseldorfTel: 49-2129-3766400

Germany - MunichTel: 49-89-627-144-0 Fax: 49-89-627-144-44

Germany - PforzheimTel: 49-7231-424750

Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781

Italy - VeniceTel: 39-049-7625286

Netherlands - DrunenTel: 31-416-690399 Fax: 31-416-690340

Poland - WarsawTel: 48-22-3325737

Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91

Sweden - StockholmTel: 46-8-5090-4654

UK - WokinghamTel: 44-118-921-5800Fax: 44-118-921-5820

Worldwide Sales and Service

03/25/14