Diagnostic System for Electronic Fuel Injection Engines

Pedro Maria de Sousa Melo Correia Duarte

(IST n. 50823)

Dissertation submitted for obtaining the degree of Master in Electrical and Computer Engineering Proposal 251/2007

Thesis Committee President: Prof. José António Beltran Gerald Advisor: Prof. Moisés Simões Piedade Members: Prof. Leonel Augusto Pires Seabra de Sousa Prof. Francisco André Corrêa Alegria

September 2007

To all of those who always fed my interest in engineering, specially my grand fathers, my uncles and my father. I would probably be a rich doctor by now if weren't for you.

i Acknowledgements

Acknowledgements

Before going into any further details of my thesis I believe that I must mention all the people and companies who made my work possible or at least eased the way as much as they could. Among these there are three special acknowledgements that have to be made to the ones whose contribution was invaluable. These are my parents and grandparents who gave me all the support they could, both financially and emotionally, throughout my academic process; my supervisor Dr. Moisés Piedade who accepted to guide my work and whose passion for electronics has been a key factor on my personal motivation on this course; and at last but not less important than the others, my colleague Paulo Louro who assisted me on every doubts I came across regarding both hardware and software development.

I must also express my profound appreciation for the following individuals: Eng. Victor Silvestre from Fatrónica, Fabrico de Artigos Electrónicos, S.A. who provided me with testing hardware for the development of the on-board car computer, Dr. Francisco Alegria who reviewed my thesis for its final presentation, Mrs. Marli Gomes and Mr. Manuel Ribeiro for the assistance with laboratory material requests, and the team of soon-to-be engineers who shared the laboratory with me and helped me to keep the good mood through the entire project.

As of communities I have to thank to all the members of the DIY community of pgmfi.org who researched the electronic control units used in engines. Without their investigation which is underway for at least 10 years it would have not been possible to achieve the results I got. I also must express my sincere appreciation for the community vtec.pt which helped me in many ways regarding the vehicle that was the subject of my research.

ii Abstract

Abstract

For the last 30 years, the automotive industry has been feeling the strong impact of electronic components in their end-products. Part of the technology that started being used for the simple control of headlights and brake lights soon became part of more complex embedded systems that reached many areas of the vehicle ranging from vital security applications to multimedia appliances. On extremely advanced vehicles the electronics and harness hardware used may reach up to 70% of the total cost of the final product.

With the growth of the concurrent market for OEM and aftermarket off-the-shelves multi-purpose devices, standards regarding communication between the vehicle and these third party appliances had to be defined. Originally developed in 1980, CAN bus was created to establish a consensus in intra-vehicle communication. It sill is one of the most successful protocols for serial communication nowadays and is already employed outside the automotive industry. However, in an age where critical functionality such as X-by-Wire tends to earn more market place, more reliable and faster buses are required.

The work presented in this paper explores one possible approach to develop a console that integrates three standards of communication with low cost interfaces. After exhaustive research CAN bus, LIN bus and USB were chosen to integrate this prototype in order to allow transmission speeds up to 1Mbps concerning the third party peripherals and up to 12 Mbps towards the vehicle on-board computer.

Although examples for all the buses were provided, the main functional objective of this thesis is to give the driver the possibility to interact with the engine ECU, using this platform, in a vehicle that was not prepared for the effect at the time of its design. The achieved result was the ability to gather real time information about the conditions of an internal combustion engine and to be able to interact with mechatronic peripherals on the fly.

Keywords

Automotive Communication, CAN bus, LIN, On-board Computer, ECU, Datalogging

iii

Resumo

Resumo

Desde há 30 anos que a indústria automóvel tem vindo a sentir o grande impacto dos componentes electrónicos nos seus produtos finais. Parte da tecnologia que começou por ser usada para o simples controlo de faróis e luzes de travagem rapidamente se tornou parte de sistemas embebidos mais complexos que afectam várias áreas do veículo, desde aplicações de segurança crítica até aplicações multimédia. Em veículos extremamente avançados, todos os componentes electrónicos e cablagem utilizados podem chegar a 70% do valor total do produto final.

Com o crescimento do mercado paralelo de peças originais ou componentes genéricos para diversos fins, protocolos de comunicação entre o veículo e estes dispositivos tiveram de ser definidos. Originalmente desenvolvido em 1980, o CAN bus for criado para estabelecer o consenso em comunicação interna automóvel. É hoje ainda um dos mais populares protocolos para comunicação em série e já é utilizado fora da indústria automóvel. Contudo, numa era onde a funcionalidade critica como o X-by-Wire tende a ganhar mais lugar no mercado, protocolos mais fiáveis e rápidos são necessários.

O trabalho apresentado neste documento explora uma abordagem possível ao desenvolvimento de uma consola que integra três protocolos de comunicação de baixo custo. Após uma pesquisa exaustiva CAN bus, LIN bus e USB foram escolhidos para integrar este protótipo de forma a permitir velocidades de transmissão até 1 Mbps considerando os periféricos automóveis e até 12 Mbps considerando o computador de bordo.

Apesar de terem sido criados exemplos para todos os barramentos de dados implementados, a principal objectivo funcional desta tese é dar a possibilidade de interagir com a ECU do motor, utilizando esta plataforma, num veículo que não está preparado para o efeito de fábrica. O resultado obtido foi a capacidade de observar em tempo real informação sobre as condições de um motor de combustão interna e conseguir interagir com periféricos mecânicos e eléctricos de forma instantânea.

Palavras-chave

Comunicaçao automóvel, CAN bus, LIN, Computador de Bordo, ECU, Registo de Dados

iv Table of Contents

Table of Contents

Acknowledgements...... ii

Abstract...... iii

Resumo ...... iv

Table of Contents...... v

List of Figures ...... viii

List of Tables...... x

List of Abbreviations...... xi

1 Introduction ...... 1

1.1 Overview...... 2

1.2 Motivation and Contents...... 3

2 Protocols ...... 5

2.1 Introduction...... 6

2.2 Protocol Overview ...... 6

2.2.1 IEBus overview – Class A ...... 6 2.2.2 Motorola Interconnect (MI) Overview – Class A...... 7 2.2.3 SAE J1708 overview – Class A...... 7 2.2.4 Local Interconnect Network (LIN) overview – Class A ...... 7 2.2.5 J1850 overview – Class A ...... 8 2.2.6 Distributed Systems Interface (DSI) overview – Class B ...... 8 2.2.7 Intellibus overview – Class B and C ...... 8 2.2.8 Controller Area Network (CAN) overview – Class B and C...... 9 2.2.9 FlexRay overview – Class C...... 9 2.2.10 Media Oriented Systems Transport (MOST) overview – Class C...... 10

v

2.2.11 On-Board Diagnostic (OBD) overview – Class C ...... 10 2.2.12 Byteflight (SI-Bus) overview – Class C...... 11 2.2.13 Bosch-Siemens-Temic (BST) overview – Class C ...... 11 2.2.14 Mobile Multimedia Link (MML) Overview – Class C...... 12 2.2.15 Domestic Digital Bus (D2B) overview – Class C ...... 12 2.2.16 SMARTwireX overview – Class C ...... 12 2.2.17 IDB-1394 overview – Class C...... 12 2.3 Protocol Selection...... 12

2.4 Protocol Specification ...... 15

2.4.1 LIN ...... 15 2.4.2 CAN bus ...... 19

3 Main Board...... 29

3.1 Chapter Overview...... 30

3.2 Hardware...... 30

3.2.1 Overview...... 30 3.2.2 ...... 30 3.2.3 Transceivers ...... 35 3.2.4 CAN Controller...... 38 3.2.5 Status LEDs...... 43 3.2.6 External Connectors ...... 43 3.2.7 Power Supply...... 44 3.2.8 Summary ...... 44 3.3 Software ...... 45

3.3.1 Introduction ...... 45 3.3.2 System configuration ...... 45 3.3.3 LIN Communication ...... 46 3.3.4 USB communication ...... 50 3.3.5 CAN communication...... 52

4 On-board Computer ...... 55

4.1 Chapter Overview...... 56

4.2 Hardware...... 56

4.2.1 Processor and screen...... 56 4.2.2 Power supply ...... 59 4.3 Software ...... 60

vi

4.3.1 Introduction ...... 60 4.3.2 Operating System...... 61 4.3.3 USB interface – C++ and ActiveX ...... 62 4.3.4 HTML Application – Graphical User Interface ...... 64

5 Example Applications ...... 65

5.1 Introduction...... 66

5.2 Applications ...... 66

5.2.1 LIN – Suspension Control...... 66 5.2.2 CAN – ECU RAM Reading ...... 75 5.2.3 CAN – Thermometers...... 89 5.2.4 Media Player...... 95

6 Conclusions and Improvements ...... 96

6.1 Conclusions...... 97

6.2 Future Enhancements ...... 98

Annex 1 - LIN Framing Structure...... 99

Annex 2 - Schematics ...... 103

Annex 3 - MCP2515 Register Description...... 108

Annex 4 - Plug-In Tutorial...... 111

Annex 5 - P30 ECU TopologyGenerators...... 118

Annex 6 - MCUs CodeGenerators...... 122

References...... 124

vii List of Figures

List of Figures

Figure 1 – LIN Master/Slave Communication...... 15 Figure 2 – Three types of Unconditional Frames...... 16 Figure 3 – Example of Event Triggered Frames involving collision...... 17 Figure 4 – Example of Sporadic Frame...... 18 Figure 5 – Can transactions...... 21 Figure 6 – CAN generic frame...... 22 Figure 7 – CAN Error frame...... 25 Figure 8 – CAN Overload frame...... 25 Figure 9 – CAN Interframe Space – Error Active Node...... 26 Figure 10 – CAN Interframe Space – Error Passive Node...... 26 Figure 11 – PIC18F4550 pin diagram...... 32 Figure 12 – Port Conflict by shared node NX...... 33 Figure 13 – Port Conflict workaround for the shared node NX...... 34 Figure 14 – MCP2551 block diagram...... 35 Figure 15 – Slew Rate characteristic as function of Rs resistance...... 36 Figure 16 – MCP201 Block Diagram...... 37 Figure 17 – MCP201 Typical Circuit...... 37 Figure 18 – MCP201 State Machine...... 38 Figure 19 – MCP2515 Block Diagram...... 38 Figure 20 – CAN Nominal Bit Time Segments...... 40 Figure 21 – LT1776 Typical Application...... 44 Figure 22 – Flowchart of the Main Routine: main...... 45 Figure 23 – Flowchart of the LIN polling routine: LinCOM...... 46 Figure 24 – Flowchart for the LIN driver part 1...... 48 Figure 25 – Flowchart of the LIN driver part 2...... 49 Figure 26 – MBP data frame...... 50 Figure 27 – VIA EDEN Processor...... 59 Figure 28 – M2-ATX power supply...... 59 Figure 29 – Flowchart of the main routine of the ActiveX C++ application...... 63 Figure 30 – Kayaba AGX sensitivity selector...... 66 Figure 31 – On-Board Computer Module...... 67 Figure 32 – Microcontroller Schematic...... 69 Figure 33 – S3003 Characteristic...... 70 Figure 34 – Flowchart of the LIN driver for Slave Task - part 1...... 71

viii

Figure 35 – Flowchart of the LIN driver for Slave Task – part 2...... 72 Figure 36 – Flowchart of Timer1 interrupt routine...... 74 Figure 37 – Layout of the user interface of the Datalogger Module...... 76 Figure 38 – Datalogger Flowchart for 1-byte commands...... 80 Figure 39 – Advanced Commands flowchart (continuation)...... 81 Figure 40 – User Registers Table for OKI 66K MCU...... 82 Figure 41 – ECU Emulator GUI...... 83 Figure 42 – RS232 interface ISR Flowchart...... 85 Figure 43 – CAN Interface ISR Flowchart...... 86 Figure 44 – Photograph of the P30 MCU...... 87 Figure 45 – Schematic of the P30 ECU custom components...... 88 Figure 46 – ECU to CAN interface...... 89 Figure 47 – Temperature interface on the GUI...... 90 Figure 48 – Flowchart of the DS18S20 driver (Part 1)...... 92 Figure 49 – Flowchart of the DS18S20 driver (Part 2)...... 93 Figure 50 – Thermometers schematic...... 94 Figure 51 - Media Player GUI...... 95 Figure 52 – Representation of the Byte Field in LIN...... 100 Figure 53 – Representation of the Frame Slot in LIN...... 100 Figure 54 – The Synch Byte in LIN...... 100 Figure 55 – The Identifier Field in LIN...... 101 Figure 56 – The Data Field in LIN...... 101 Figure 57 – Schematic of the Main Board...... 104 Figure 58 – Schematic of the ECU Datalogger ...... 105 Figure 59 – Schematic of the Thermometer Board ...... 106 Figure 60 – Schematic of the Suspension Board...... 107 Figure 61 – Detail photograph of the MCU and external EEPROM inside the ECU...... 119 Figure 62 – Photograph of Complete Signal Processing area...... 120 Figure 63 – Photograph of Complete Signal Conditioning Area...... 120 Figure 64 – Photograph of ECU connector part A B and C...... 121 Figure 65 – Identification of the pins of ECU connector A...... 121 Figure 66 – Identification of the pins of ECU connector B and C...... 121

ix List of Tables

List of Tables

Table 1 – Class B protocols comparison...... 13 Table 2 – Class C protocols comparison...... 14 Table 3 – Class C protocols comparison (continuation)...... 14 Table 4 – Datal Length Code Combinations...... 23 Table 5 – VIH and VIL for MCP2515 pin SI...... 34 Table 6 – CAN Time Quanta Distribution...... 42 Table 7 – Led Blinking Code...... 43 Table 8 – MBP Fields Description...... 50 Table 9 – Type Field values...... 50 Table 10 – Bus Field Values...... 51 Table 11 – VIA processor comparison table...... 58 Table 12 – Suspension Module Messaging...... 68 Table 13 – Map of sensor displays...... 76 Table 14 – Datalogger Module Messaging...... 77 Table 15 – RAM Addresses of Sensor Data...... 78 Table 16 – CN2 Connector Pinout...... 88

x List of Abbreviations

List of Abbreviations

ABS Anti-lock Braking System BRP Baud Rate Prescaler BST Bosch-Siemens-Temic CAN Controller Area Network Bus CARB California Air Resources Board CEL Check Engine Light CRC Cyclical Redundancy Check D2B Domestic Digital Bus DIY Do It Yourself DLC Data Length Code DSI Distributed Systems Interface DSP Digital Signal Processor DTC Data Trouble Codes ECU Electronic Control Unit EFI Electronic Fuel Injection ELD Electrical Load Detector EMC Electromagnetic compatibility EOC Electrical Optical Converter EOD End of Data EOF End of Frame EUSART Enhanced Universal Synchronous Asynchronous Receiver FIFO First In First Out GUI Graphical User Interface GUID Globally Unique Identifier HDD Hard Disk Drive Hex Hexadecimal HS High-Speed HTA HTML Application HTML Hyper Text Mark-up Language I/O Input/Output IC Integrated Circuit IF Interruption Flag IFR In-Frame Response ISO International Organization for Standardization

xi

KWP2000 LED Light Emitting Diode LIN Local Interconnect Network LSB Least Significant Bit MBP Multi Bus Protocol MCU Micro-controller Unit MI Motorola Interconnect MIL Malfunction Indicator Light MOST Media Oriented Systems Transport MSB Most Significant Bit NA Not Available NAD Node Address for Diagnostic NBR Nominal Bit Rate OEC Optical Electrical Converter OF Overflow Flag OLED Organic Light Emitting Diode OS Operating System PCB Printed Circuit Board PLL Phase-Locked Loop POF Plastic Optical Fibre POR Power-On Reset PWM Pulse Width SAE Society of Automotive Engineers SDI Serial Data In SDO Serial Data Out SJW Synch Jump Width SJW Synchronization Jump Width SOF Start of Frame SPI Serial Peripheral Interface TDM Time Division Multiplexing TDMA Time Division Multiple Access TQ Time Quanta TTL Transistor – Transistor Logic US United States (of America) USB Universal Serial Bus VPW Variable Pulse Width

xii Chapter 1

Introduction

1 Introduction

1 1.1 Overview

For the last 30 years the impact of electronic components in the automotive industry has increased dramatically.

According to CommonWealth Magazine [1], in the year of 2005 the automotive industry gross output reached 630 million US dollars from which 20% are due to electronic components (approximately 124 million US dollars) and this is expected to grow to 35% in 2008.

With this increased volume of electronic systems ranging from central door locking, anti-lock breaking, rain detectors, tire pressure sensors, X-by-wire, active suspension, GPS alarm systems, cruise control among many others, it is of the utmost importance to reach a consensus in terms of internal communication. Many of these appliances are sold by third party companies and therefore may require major modifications to the vehicle in order to work properly.

Since the early 80’s that an effort has been made towards internal automotive communication. Robert Bosh GmbH developed on 1980 the Controller Area Network bus, a very successful protocol that is still largely used as a standard of electronic signal transmission not only on the automotive industry but in many other areas as well. Its key features were being multi-master, having high-speed (up to 1 Mbps) and having high noise immunity.

With the migration of multimedia systems to the automotive environment, the need for a larger bandwidth increased. 10 years ago, in 1997, the Media Oriented Systems Transport (MOST) technology started to be developed by Oasis Silicon Systems AG in cooperation with renowned automotive brands such as BWM and DaimlerChrysler. MOST development is currently under the responsibility of MOST Cooperation and allows baud rates up to 64 Mbit/s per second and it is the current main protocol used to deliver multimedia functionality to vehicles.

As for reliability a new approach had to be developed. Most critical systems such as Brake-By-Wire and Steer-By-Wire required that the data had to be delivered to the final actuator with virtually no margin for error. Once again an experts group was created in order to establish a new standard and in 2000 BMW, DaimlerChrysler, Philips and Motorola formed the FlexRay Consortium. Now extended to seven core members The FlexRay Consortium expects to certify FlexRay for full use in 2008 [2]. The protocol relies on stronger multi sampling of each transmitted bit and strict clock synchronization constraints between nodes.

Another concept of great interest is the On-Board Diagnostic (OBD) which was initially developed for increased control over the vehicle emissions. Although the concept was broadly accepted, the communication standard was not defined and most brands implemented their own version of OBD. It

2

was only in 1994 that OBD-II protocol was finally specified and in 1996 considered mandatory on all vehicles on the United States. OBD-II standard specifies the type of diagnostic connector, its pinout, the electrical signalling protocols available, and the messaging format. The specification allowed that any single device that could connect to an OBD-II connector could read the diagnostic data of an automobile produced later than 1996.

Regarding software, major changes took place in the automotive industry as well. With the introduction of Microsoft Windows CE 6.0 and its automotive-oriented distribution [3] - Windows Automotive - the power of high-level and object oriented programming languages can be brought to user interfaces and signal processing routines. GPS navigator software, multimedia applications and user friendly interfaces among others are now possible with Microsoft’s well known engines.

1.2 Motivation and Contents

Until now most of the communication done between the ECUs of the various connected systems in a vehicle focused only on brand-specific hardware. Third party components are somehow discouraged and major modifications on the vehicles have to be made in order to make these devices work.

This thesis goes against this conservative position. The main goal expected to be achieved with it is to develop a console that allows different devices to be connected to a central computer independently of the protocol used.

Because a greater level of both controllability and observability over the vehicle is sought, there is a need to explore its internal communication with various sensors as well as with its engine. Although all recent vehicles are required by law to be equipped with a diagnostic port (OBD-II protocol), the vehicle used for this project is older than 1996 and therefore is not equipped with such connector. Therefore, intrusive hacking had to be done.

The current state-of-the-art for this type of platforms is not available for the end user. The first consoles of this kind appeared in late 2006 with the German company GOEPEL and provided functionality to test systems through different protocols such as CAN, LIN or K-line [4]. As far as the end user is concerned there is no alternative to connect his automobile to the various buses and visualize the nodes activity on a personal computer.

This project consisted on three distinct hardware modules:

• An On-board Computer which will be the only interface with the driver;

• A Main Board which will communicate with the On-board Computer and translate its commands to the destination protocols;

3

• The example applications which will be hooked to one of the buses and process the commands sent by the Main Board. In case where a response is expected, these applications will provide it.

This document is structured in the same order that the project was carried out.

• On chapter 2 several of the existing protocols will be compared in order to select two protocols to implement. The selected protocols will be explained in detail as well.

• On chapter 3, the hardware and software for the main board will be explained.

• On chapter 4, the software and hardware for the on-board computer will be focused.

• On chapter 5, the example applications will be explained in detail. There will be an application for strut control using the LIN bus, an application for engine ECU diagnostic using CAN bus and another application for CAN bus for temperature reading inside and outside of the vehicle.

• On chapter 6, the conclusions of the thesis will be listed as well as suggestions for future improvements and upgrades.

4

Chapter 2

Protocols

2 Protocols

5 2.1 Introduction

During the last three decades several attempts to standardize popular protocols used in automotive industry have been made. There is no such thing as a perfect protocol since most systems have unique requirements and some aspects of them are opposed to key aspects of others. Wideband for multimedia applications, such as the needed by MOST clusters, often require the use of optical fibre which drives to more expensive systems than low cost buses such as LIN or CAN. Also reliable protocols such as FlexRay require data bits to be sampled during multiples clock cycles in order to achieve a greater level of trust over the received signal, sacrificing the maximum baud rate that could be reached with that medium.

In order to clarify the role of each bus, SAE has defined three classes of protocols concerning bit- rates: Class A, B and C [5].

• Class A protocols are low speed buses and are not supposed to go much higher than 10 kbps. These are mostly used for smart sensors and non-critical control and most of them are proprietary.

• Class B protocols are medium speed, mostly between 10 up to 125 kbps. These are used for emission diagnostic, instrument clusters, and highly multiplexed systems.

• Class C protocol are high speed protocols, ranging from 125 kbps to several Mbps. Class C protocols are used mainly for entertainment and critical and real-time control such as X-By- Wire or real-time programming of the ECU.

On this chapter several of the protocols used in automotive industry will be analysed and compared in order to choose two to be implemented. A more careful analysis of the selected buses will be made on the next chapter.

2.2 Protocol Overview

2.2.1 IEBus overview – Class A

IEBus represents NEC’s position in the automotive industry of low speed serial networks. It supports multi master communication with CSMA/CD for access control. It requires a 2-wire differential line and

6

the operation speed depends on the selected mode ranging from 3.9 kbps to 18 kbps. A good advantage of this technology is the supports of up to 50 nodes over a maximum bus length of 50 meters.

2.2.2 Motorola Interconnect (MI) Overview – Class A

Motorola Interconnect, much like LIN, uses only one wire, one master and is used to connect peripherals such as mirrors, door looks and seats.

Unlike LIN, MI supports only a maximum of 8 slave nodes. This protocol has serious limitations on the amount of data that is allowed be sent. The master is allowed to send 5 bits of data while the slave can respond with up to a maximum of 3 bits of data. The bit rate is typically 20 kbps.

Although similar to LIN, obvious limitations such as low capacity for data volume and lack of support for systems with more than 8 nodes make it an obsolete standard.

2.2.3 SAE J1708 overview – Class A

J1708 uses RS485 bus as the electrical layer. Requires a 2 wire medium with a maximum distance of 40 m and operates at 9600 bps. Supports messages up to 21 characters and has a 2 bytes header. It also uses Master/Slave topology and an 8 bit error detection system.

It is a medium cost bus used for control and diagnostic applications.

2.2.4 Local Interconnect Network (LIN) overview – Class A

Local Interconnect Network [7] is a concept for low cost automotive networks, which seeks to complement the existing technologies available. It is a fairly recent protocol with its first specification version (v1.1) being released in 1999 and its last version (v2.1) released in 2007 under the enforcement of LIN consortium. LIN is intended to be used as a sub bus on CAN networks, although this is not mandatory, allowing the creation of hierarchical networks and therefore reducing the cost of development, production, service and logistics in vehicle electronics.

LIN bus supports up to 16 nodes including the master on a maximum bus length of 40 m and bit rates up to 19.2 kbps. Contrary to CAN, LIN supports multiple nodes on the same bus working at different baud rates. This is possible due to the single master restriction. Each slave node must respond to the requests of the master and only the master is allowed to start a new frame. After the break symbol the master sends a synchronization byte that allows the respective nodes to synchronize with the new frame bit rate.

The protocol supports the transport of data from 1 up to 4095 bytes. However, this latter is only used on node configuration, identification and diagnostics. The normal data transfers range from 1 up to 8

7

bytes of data. Each frame has checksum protection but no collision detection for unconditional frames (the simplest type of frame where the master issues one request and a single slave must respond).

LIN supports remote node configuration giving the master the possibility to configure any node that is connected in the bus. In order to maximize compatibility with Plug & Play functionality, as of version 2.0 the LIN Consortium assigns each registered product with a unique LIN product ID.

LIN has seen its popularity grow largely on this last five years and it is becoming the new standard for low cost, multiplexed automotive systems such as door locks, lighting control and multipurpose-sensor data gathering among others.

2.2.5 J1850 overview – Class A

J1850 is one protocol for serial data transmission. It is employed in OBD-II communication.

It can operate at either 41.6 kbps with PWM in a two wire differential approach or at 10.4 kbps with VPW in a single wire approach. The single wire approach has a maximum bus length of 35 meters and supports up to 32 nodes.

The logical High level is defined from 4.25 V up to 20 V and low is any voltage level below 3.5 V. In the single wire approach values are sent as bit symbols (not single bits) meaning that 1 in active (dominant mode) has a different time length than a 1 in passive mode. Values are sent as either 64 µs or 128 µs pulses.

J1850 was developed and in 1994 and never gained much popularity since it is a direct rival of CAN. The two main reasons accounted for its failure are the lower bit rate and the fact on being only used in the United States of America.

2.2.6 Distributed Systems Interface (DSI) overview – Class B

DSI is one of the first safety-critical protocols developed by Motorola. It is a 2-wire serial bus and uses a Master/Slave approach with data rates up to 150 kbps and uses 3-level voltage. It has CRC protection for error detection. It is mainly used for airbag systems just like BST. It has a maximum capacity of 16 nodes.

TRW – a popular automotive safety systems manufacturer – has been developing solutions using DSI architecture and the development of new devices is being stimulated since development. It is a royalty free technology.

2.2.7 Intellibus overview – Class B and C

Intellibus was developed by Boeing initially for military avionic applications. However, it saw

8

application in the automotive field as well. It has a maximum bit rate of 12.5 Mbps, uses a master/slave approach with Manchester encoding over a twisted pair. The maximum bus length is 30 m at 12.5 Mbps to a maximum of 64 nodes. Intellibus implements CRC and parity check which allows it to be used in appliances ranging from electronic engine control to X-by-Wire systems.

2.2.8 Controller Area Network (CAN) overview – Class B and C

Controller Area Network [6] (CAN) is a differential serial bus standard initially developed for connecting ECUs in automotive environments by Developed Robert Bosh GmbH. CAN bus was designed to be robust in electromagnetic noisy environments and can boost even more this resilience when used over a twisted pair wire.

It has a maximum bit rate of 1 Mbps (limited to a maximum bus length of 40 m) and a minimum bit rate of 10 kbps (limited to a maximum bus length of 1000 m). Although it can operate at different bit rates, CAN nodes on the same bus must all work at the same speed.

The protocol is best suited for control signals and therefore the messages are small, comprising a maximum of 8 bytes. Each frame is also protected by CRC and error handling mechanisms that guarantees data consistency assuring that the message is simultaneously accepted either by all nodes or by no node at all.

CAN is also extremely flexible and allows new nodes to be added to the bus without any necessary changes in the software or hardware of any other node or application layer. Hence the support for the multi master feature which allows any node to start transmission as long as the bus is idle.

The crescent popularity of CAN demanded a later version in the early 90s where the original 11 bit identifier was increased to 29 bits.

The success of CAN led to the employment of the standard on other industries where transmission of control signals was required. It is probably the most used bus for serial communication on industrial environments where electromagnetic noise is a concern.

2.2.9 FlexRay overview – Class C

FlexRay arises from the need for reliable hi-speed data protocol for vital functionality such as X-by- Wire. It was in 2000 that BWM, DaimlerChrysler and Motorola started developing this new protocol. Intended to use either shielded or unshielded twisted pair medium, it has a high bit rate, time-triggered behaviour, implements redundancy and is fault-tolerant.

FlexRay relies on exhaustive bit sampling, sampling eight times each received bit. It also enforces strict constraints regarding each node’s clock synchronization with the nominal clock. The maximum bit rate is 10 Mbps and it is a point-to-point protocol implemented on star topology.

9

FlexRay is expected to be fully operational by 2008 and so far the only application where it has been used in the automotive market was the pneumatic damping system of the BWM X5. Therefore, FlexRay is still considered in development and represents an extension of the successful ByteFlight protocol. Cost of its implementation is superior to most, if not all, of the actual communication buses and it is expected to be used exclusively on critical systems such as the ones mentioned above.

2.2.10 Media Oriented Systems Transport (MOST) overview – Class C

In 1997 Media Oriented Systems Transport (MOST) technology started to be developed by Oasis Silicon Systems AG in cooperation with renowned automotive brands such as BWM and DaimlerChrysler.

MOST standard is currently developed by MOST Cooperation and allows baud rates up to 25 Mbps. It is the current protocol of choice for multimedia systems on automotive industry. Intended to be implemented over Plastic Optical Fibres (POF) MOST requires a point-to-point architecture and is implemented in a ring topology. Although it requires optical fibre mediums, MOST standard was designed to create low cost networks for multimedia delivery.

MOST supports up to 64 connected devices and multi master behaviour. However, all nodes must have its clock synchronized with a single timing master. MOST uses Time Division Multiple Access (TDMA) for frame transport and three types of data inside each frame: Streaming, Packet and Control. Within the synchronous base data signal, multiple streaming data channels and a control channel are transported. The transport channel specifies which streaming data channels the master and the slave will be using and once this is set up no more configuration information is sent. Data can flow continuously, without any collisions, interruptions or slow-downs in the data stream. In order to accommodate asynchronous data packet communication such as Internet traffic MOST implements a mechanism to emulate asynchronous communication on top of the synchronous data signal.

2.2.11 On-Board Diagnostic (OBD) overview – Class C

On-Board Diagnostics is a standard developed to diagnose system malfunctions and control CO2 emission in modern automobiles.

OBD-II supports five different communication protocols although manufacturers are only forced to implement one. Each protocol uses a different pinout making the diagnostic a difficult task for most auto repair stations. To resolve this problem, in 2008 all vehicles in the US will be required to use at least the standard ISO 15765-4, a variant of CAN bus, in their OBD-II diagnostic port.

The five supported protocols are:

10

SAE J1850 PWM, used mainly by Ford Company (41.6 kbps). The communication is done with Pulse Width Modulation (PWM).

SAE J1850 VPW, used by General Motors (10.6 kbps). Communication is done with Variable Pulse Width.

ISO 9141-2, used by Chrysler, European and Asian vehicles has a 10.4 kbps rate and it is similar to RS-232.

ISO 14230 KWP2000, (Keyword Protocol 2000 has data rates between 1.2 and 10.4 kbps and is able to contain up to 255 bytes in the data field.

ISO 15765, CAN. Can has a maximum baud rate of 1 Mbps, a maximum of 8 data bytes in data field and it is the most popular standard for serial, low cost communication in the automotive industry.

In addition to the DTC, OBD standard also suggests a led in the often called as Malfunction indicator light (MIL) or Check Engine Light (CEL). When the CEL is on, auto-service is required to discover the cause of the malfunction.

2.2.12 Byteflight (SI-Bus) overview – Class C

Byteflight was one of the first attempts to create a fault-tolerant protocol to be used on safety-critical applications. It was developed by BWM with Motorola, Elmos and Infineon. A typical application is an airbag system which requires fast response time and low overhead. Byteflight is extremely flexible and controllers can be found off-the-shelf nowadays.

It uses either 2 or 3 wires buses and at a data rate of 10 Mbps. The protocol uses Time Division Multiple Access (TDMA) and uses POF as the medium in a star topology. The protocol supports up to 12 data bytes and has CRC protection.

Although meant to be used on automotive industry, this standard was already implemented in aircraft systems by Avidyne. Byteflight was used on BMW serie 7 for Shift-By-Wire applications in 2001 but tends to be replaced by its extension - FlexRay - as soon as 2008.

2.2.13 Bosch-Siemens-Temic (BST) overview – Class C

BST is another standard for safety-critical applications and is used mainly in airbag systems.

It has a low bit-rate reaching a maximum of 250 kbps on a 2 wire bus. Uses Manchester encoding and implements either Parity or CRC for error detection. The data field has a 1 byte length

Although a low cost bus, it is not supposed to be used in systems other than airbags.

11

2.2.14 Mobile Multimedia Link (MML) Overview – Class C

MML is a multimedia bus that reaches up to 110 Mbps. It is a fault-tolerant protocol that uses master/slave architecture over POF in a star topology network. It uses NRZ encoding and supports plug and play functionality.

MML is a direct rival of MOST buses and has a low overhead of 5% - 10%. However, the bus length is limited to 10 meters and has a limit of 16 nodes.

2.2.15 Domestic Digital Bus (D2B) overview – Class C

Domestic Digital Bus is an optical solution for multimedia data deliver. It has a capability of 25 Mbps however it is only been used in some Mercedes models with bandwidths up to 5.6 Mbps. The maximum fibre distance is 10 meters when using one coupler and it has been used in star and ring topologies. It is mainly used with SMARTwireX.

2.2.16 SMARTwireX overview – Class C

SMARTwireX is an electrical solution for automotive networks. It defines a physical layer intended to support D2B networks running up to 25 Mbps over standard low-cost UTP cabling, with full automotive EMC compatibility. Although initially designed for D2B electrical networks it is capable of supporting other networks as well. SMARTwireX uses a Master/Slave approach connected via twisted pair, encoded as PWM and has a maximum bus length of 150 m supporting up to 50 nodes. The disadvantage is the high cost of implementation.

2.2.17 IDB-1394 overview – Class C

IDB-1394 is the FireWire attempt to integrate the automotive industry. It follows IDB-C which was an attempt to create in-vehicle networks using CAN 2.0B, reaching a maximum bit rate of 250 kbps, supporting up to 16 nodes, 8 bytes of data length and 15 bit CRC.

2.3 Protocol Selection

On this section the protocols described will be compared and a decision will be made towards the protocols to be used for the application.

The success of a protocol has much to do with the companies behind it. Nowadays brands like BMW, Motorola, Tyco and DaimlerChrysler have a great weight on future standards for the industry.

12

Application areas for these protocols can be roughly divided into 3 key areas:

• Safety-Critical applications such as X-by-Wire

• Multimedia appliances such as video and audio delivery.

• Sensor data transmission and actuator control signals, such as electrical mirror operation, central door lock mechanisms or engine coolant temperature reading.

While on the first area – safety-critical applications – Byteflight has proven reliable, a new extension to the protocol is about to be made available for automotive designers, FlexRay. FlexRay is the new bet of BWM and Motorola and is believed to be the new standard for vital applications. The other protocols focused: DSI and BST are exclusively used on airbag systems and are limited by either their bit rate or error mitigation.

On multimedia applications MOST is gaining popularity. This protocol has good specifications such as support to up to 64 nodes, synchronous and asynchronous data transmission and several data streaming channels. Once again this protocol is supported by BMW and DaimlerChrysler. The other competitors are D2B and MML. D2D has a low bit rate for the current multimedia needs and MML requires optical fibre solutions while MOST support copper mediums.

As for sensor output sampling and actuator control CAN is still the most popular protocol. The serious limitation of CAN of a maximum of 16 nodes led to the creation of sub networks. On these sub networks the most successful standard is LIN since the low bit rate, 1 wire medium and master/slave approach allow for lower cost nodes. Also LIN supports hierarchical reports and plug and play functionality based on real time node configuration. Its competitors are almost brand exclusive protocols such as J1850 used by Ford and General Motors or too high cost for these kind of applications like J1708.

The following tables [8] summarize the main characteristics of these protocols that were used to judge the best candidates. The values followed by an asterisk represent typical values when the official specification does not specify them. Whenever a value is not given by the specification or the specification is not public to consult them the value is set to NA – Not Available.

Table 1 – Class A protocols comparison.

J1708 LIN MI IEBus J1850-X

Affiliation TMC-ATA Motorola Motorola NEC GM, Ford

Application Control & Diagnostic Smart Sensors Smart Sensors Control & Diagnostic General & Diagnostic

Media Twisted Pair Single Wire Single Wire Twisted Pair Single or Twisted P.

Error Detection ACK CRC NA ACK CRC

Overhead 45% 2 Bytes NA NA 33.3%

Bit Rate 100 kbps 20 kbps 20 kbps 18 kbps 10.4 / 41.6 kbps

13

Bus length NA 40 m NA 50 m 35 m

Max nodes NA 16 8 50 32

Cost Medium Low Low Low Low

Popularity Medium High Medium Medium Medium/High

Table 2 – Class B/C protocols comparison.

CAN IDB-C MOST MML D2B

Affiliation Bosch, Sae, ISO SAE Oasis Delco C&C

Application Control & Diagnostic Aftermarket Entertainment Stream Data Stream Data Stream

Media Twisted Pair 2 wire POF, twisted pair Optical Fibre Twisted Pair

Error Detection 16-bit CRC 15-bit CRC CRC Correcting Parity

Overhead 10-22% 32 bits NA 5%-10% NA

Bit Rate 1 Mbps 250 kbps 25 Mbps 110 Mbps 25 Mbps

Bus length 40* m NA NA 10 m 150 m

Max nodes 32 * 16 64 16 50

Cost Medium Low High High High

Popularity High Medium High Medium Medium

Table 3 – Class B/C protocols comparison (continuation).

FlexRay Byteflight BST IntelliBus DSI

Affiliation Motorola, BMW BMW Bosh, Siemens Boeing Sae Motorola

Application Safety Control Airbag Airbag Control & Diagnostics Airbag

Media Twisted Pair of fibre 2 or 3 wire, optical 2 wire Twisted Pair 2 wire

Error Detection 24 bit CRC 16-bit CRC CRC, Parity CRC, Parity 4-bit CRC

Overhead 3%-100% NA NA 18%-75% NA

Bit Rate 10 Mbps 10 Mbps 250 kbps 12.5 Mbps 150 kbps

Bus length NA NA NA 30 meters NA

Max nodes NA NA 62 slaves 64 16

Cost Medium Low Low Medium Low

Popularity High High Medium Medium Medium

Based on the protocol popularity and application-orientation the elimination process led to the implementation of CAN bus as a SAE Class C protocol and LIN as a SAE Class B protocol. Class C protocols with potential for entertainment and safety applications such as MOST or FlexRay will not be implemented due to its high cost node. However, a future version of the Main Board could implement them.

14

2.4 Protocol Specification

2.4.1 LIN

2.4.1.1 Overview

LIN [7] is a serial communication protocol designed to support the control of mechatronics nodes in distributed automotive applications.

The LIN cluster comprises a single master and up to 15 slaves. The master node includes a master task as well as a slave task while all other nodes only include the slave task. It is the master task that decides when and which frame shall be transferred. In order to do this task efficiently, the master has one or more schedule-tables with the time-triggered messages to be sent.

Event trigger behaviour may be implemented with the dynamic change of the active schedule table if the master is able to determine events on its own. The schedule tables specify the identifiers for each header and the time interval between the start of frame for each header.

There are two important concepts regarding the role of each slave: Publisher and Subscriber. The publisher is the task that outputs data onto the bus on a frame slot. The subscriber or subscribers are the node or nodes that make use of the information posted on the bus. Erro! A origem da referência não foi encontrada. depicts the data transfer of two different messages, each for a different slave task.

Figure 1 – LIN Master/Slave Communication

This architecture allows for three main advantages:

• System Flexibility: New nodes may be added to the network without any change on the existing slaves.

• The Message Routing: the header issued by the master specifies a message ID which is subscribed by one or more slaves.

15

• Multicast: All nodes maybe subscribe a certain ID and therefore simultaneously receive and act upon a single frame.

As for data transport, two types of messages may be transmitted: Signals and Diagnostic Messages. Signals are scalar values or byte arrays packed into the data field of each frame. The signal position is static for frames with the same identifier. Diagnostic Messages are carried in frames with reserved identifiers and its interpretation depends on the data field itself.

Byte endianness on entities larger than one byte represented by byte arrays are out of the scope of the LIN specification and so is the interpretation of byte arrays. However within scalar signals, LSB is transmitted first and the MSB last.

2.4.1.2 Frame Transfer

Entities transferred on the LIN bus are called frames. In order to illustrate the protocol framing structure, several frames of interest will be listed and explained in Annex 1.

2.4.1.3 Frame Types

LIN frames are divided onto 6 different types: • Unconditional Frames • Event Triggered Frames • Sporadic Frames • Diagnostic Frames • User Defined Frames • Reserved Frames

Unconditional Frames

Unconditional frames are the most used and always carry signals. They are allowed to use any of the identifiers ranging from 0 up to 59. The slave task responsible for the publishing of the frame should always provide a response to the header. All subscribers of the frame should receive the response and make it available to the application.

Figure 2 – Three types of Unconditional Frames.

16

On Figure 2 three types of Unconditional Frames are represented. On the first one the Master Task is the subscriber and the Slave Task 1 is the publisher. On the second case the Master Task is the publisher and both Slave Tasks are the subscribers. On the third case the Slave Task 2 is the publisher and the Slave Task 1 is the subscriber.

Event Triggered Frames

LIN is a time-triggered protocol and it can only emulate some kind of event triggered behaviour. LIN emulated Event-Triggered behaviour with periodic polling of multiple slaves at once. The identifier range available to Event Triggered Frames is from 0 to 59.

In order to determine the origin of the response, since multiple slaves may reply to the frame Header, the first byte of the data field is the Protected Identifier of the replying slave. This enforces a maximum of 7 data bytes for the message data. Also a publisher should only provide a response if the queried signal has changed since last transmission.

If more than once slave respond to the Header, a collision will occur and the Master will have to issue a sequence of all the Unconditional Frames that are comprised by that particular Event triggered Frame. Subscribers of those responses should treat the frames as Unconditional Frames and make the responses available to the application (if the checksum was validated).

Figure 3 – Example of Event Triggered Frames involving collision.

On the Figure 3 the first attempt to fetch information from an Event Triggered Frame (ID=0x10) resulted on a collision from both publishers. The Master Task detects the collision and queries each publisher independently for the Unconditional Frames comprised within Event Triggered Frame 0x10. The master task queries once again all publishers for the same Event Triggered Frame but this time there are no changes to be reported to the subscribers. There is a third attempt to query the publishers of the frame with ID 0x10 and this time only Slave Task 2 has a change to report.

Sporadic Frames

The purpose of Sporadic Frames is to blend some dynamic behaviour into the deterministic and real- time focused schedule table. The legal identifier range available for Sporadic Frames is from 0 to 59.

17

Sporadic Frames assume some awareness of the Master regarding the status of some signals. In these cases the Master will reserve a Frame Slot for these sporadic signals. Whenever the Master believes that a signal has changed, it uses this slot to query the respective publisher. If more than one Sporadic Frame is associated with the same frame slot, the most prioritized of the Sporadic Frames will be queried. If none of the Sporadic Frames associated with the frame slot has an updated signal the frame slot shall be silent.

Figure 4 – Example of Sporadic Frame.

On Figure 4, as soon as the Master is aware of a change in the system he publishes a sporadic frame for all the concerned subscribers.

Diagnostic Frames

Diagnostic Frames always carry diagnostic or configuration data. The identifier is either 60 (on a master request frame) or 61 (on a slave response frame). The publishing, subscribing and Header transmission of the Diagnostic Frame must be authorized by each task diagnostic module.

User Defined Frames

User Defined Frames carry any kind of information and use the identifier 62. The Header of a user- defined frame is always transmitted when a frame slot allocated to the frame is processed.

Reserved Frames

Reserved Frames should not be used in a LIN 2.0 cluster and their identifier is 63.

2.4.1.4 Network Management

Network management in a LIN cluster refers to cluster wake-up and goto-sleep only.

LIN supports two modes to enter a Sleep Mode. If the LIN bus is idle for more than 4 seconds the slave nodes should automatically enter Sleep Mode. Also if the master sends a Diagnostic Master Requests frame with the first byte equal to zero (0) all slaves must enter Sleep Mode. To this special use of the Diagnostic frame is given the name go-to-sleep-command.

18

As for wake up, any node in a sleeping cluster may request a wake up. The wake up request is issued by forcing the bus to the dominant state from 0.25 ms up to 5 ms. Any sleeping node should be able to detect a dominant pulse longer than 0.15 ms and be ready to listen to bus commands within 100 ms. The Master should also wake up and start sending headers as soon as the nodes are ready. Nodes may retransmit the wake-up request up to 3 times if the Master did not start sending new Headers. After the third attempt the slave task should wait a minimum of 1.5 seconds before the next attempt.

2.4.2 CAN bus

The Controller Area Network [6] is a serial communications protocol which efficiently supports distributed real-time control with very high level of security. Its domain of applications ranges from high-speed networks to low cost multiplex wiring. In the automotive electronics industry, CAN appears as a cost effective way to replace the wiring harness required for vehicle body electronics. CAN protocol has a set of properties which define it as the main protocol used for serial communication in the automotive business:

• Prioritization of messages

• Configuration flexibility

• Multicast reception with time synchronization

• System wide data consistency

• Multi-master

• Error detection and signalling

• Automatic Retransmission of corrupted messages as soon as bus is idle

• Distinction between temporary error and permanent failures of nodes and autonomous switching off of defect nodes.

2.4.2.1 Frame Transfer

Information on the bus is sent in fixed format messages of different but limited length. As soon as the bus is idle any node may start the transmission. The bus in CAN communication can carry two complementary logic values: dominant and recessive. If during transmission (most likely during arbitration) both dominant and recessive values are sent to the bus, the dominant logic value will prevail.

19

Message Routing

In a CAN cluster nodes do not make any use of the system configuration allowing multiple nodes to be added to the cluster without requiring changes in the hardware or software of any node. The routing is made using the message Identifier. Although the Identifier does not indicate the destination of message it describes its content so all nodes decide by message filtering whether to accept it or not.

Message Filtering allows for multicast to be implemented as well. Any node may send a message and according to its contents any number of nodes may accept it or not.

CAN implements Remote Frames. By issuing a remote frame with a certain Identifier any node is requesting another node in the cluster to send the corresponding Data Frame.

Message Arbitration

Message Arbitration is based on each message Identifier. Whenever the bus is free any unit may start transmitting. If 2 or more nodes start their message at the same time the bus access conflict is resolved by bitwise arbitration using each message Identifier. Two different types of conflict may arise: A conflict between a Remote Frame and a Data Frame and a conflict between two frames of the same type. Whenever a Remote Frame disputes the bus with a Data Frame, the Data Frame prevails. Otherwise, during arbitration, the transmitter must compare the logic level of the current bit on the bus with the bit he supposedly sent. When the transmitter sends a recessive level and monitors a dominant level, the transmitter assumes that another node with a higher priority message is competing for bus access and withdraws.

Error detection and handling

CAN is considered a fairly safe protocol and in spite of not being fully trusted for X-by-Wire applications it implements several mechanisms for error detection and data integrity protection.

For error detection CAN implements:

• Monitoring while transmitting

• Cyclic Redundancy Check (CRC)

• Bit Stuffing

• Message Frame Check

For performance of error detection:

• All global errors are detected

20

• All local errors at transmitters are detected

• Up to 5 randomly distributed errors in a message are detected

• Burst errors of length less than 15 in a message are detected

• Errors of any odd number in a message are detected

Sleep Mode / Wake-up Mode

CAN also implements a low power consumption mode without any internal activity and with disconnected bus drivers. The Sleep Mode is finished with a Wake-up by any bus activity or by internal conditions of the system. The bus drivers will be set to “on-bus” state again once the system’s oscillator has stabilize and after checking 11 recessive bits on the bus.

The following picture, Figure 5, illustrates an ordinary transaction of messages in a CAN cluster.

On this example Node 1 has priority over Node 2 and Node 3 has priority over all. On the SoF Node 1 and Node 2 start transmitting but node 2 looses arbitration to Node 1. On the second SoF Node 1 starts transmitting and so does Node 3. Node 1 looses arbitration to Node 3 who continues its transmission. On the third SoF Node 2 transmits alone and so is able to finish its message.

The red areas represent what was supposed to be transmitted but was not due to loss of bus access during the arbitration. The Node 1 frames are represented in grey; Node 2 frames represented in blue; Node 3 frames represented in Green.

Figure 5 – Can transactions.

2.4.2.2 Frame Types

The CAN protocol defines 4 different types of frames:

• Data frames

• Remote Frames

21

• Error Frames

• Overload Frames

The frames in CAN are made of up to seven different bit fields:

• Start of Frame

• Arbitration Field

• Control Field

• Data Field

• CRC Field

• ACK Field

• End of Frame

Figure 6 – CAN generic frame.

Start of Frame

Start of Frame marks the beginning of Data Frames and Remote Frames and consists of a single dominant bit. A node is only allowed to start transmission when the bus is idle and must send this symbol as the first step in communication. All other nodes must synchronize to the SOF.

Arbitration Field

The Arbitration Field consists of an 11 bit Identifier in Standard Format and of a 19 bit Identifier in Extended Format. In order to distinguish between both standards the reserved bit r1 in CAN 1.0-1.2 is not denoted IDE bit.

On the Standard Format the Identifier length is 11 bits and corresponds to the Base ID in the Extended Format. These bits are transmitted in the order from ID-28 – ID-18 with the least significant

22

bit being ID-18. The 7 most significant bits (ID-28 – ID-22) must not be all recessive.

On the Extended Format, in contrast with the Standard Format, there are 29 bits divided into 2 groups: Base ID (11 bits) and Extended ID (18 bits). The Base ID is transmitted in the order from ID-28 to ID-18 and is equivalent to the format of Standard Identifier. The Base ID defines the Extended Frame’s base priority. The Extended ID consists of 18 bits and it is transmitted in the order of ID-17 to ID-0.

RTR Bit – Remote Transmission Request Bit

In DATA Frames the RTR Bit must be dominant to prevail over a Remote Frame with the same Identifier in the Arbitration process. In a Remote Frame must be recessive.

SRR Bit – Substitute Remote Request Bit

The SRR Bit only exists in Extended Frames and is always recessive. It takes the position of the RTR Bit in the Standard Format Frames so that a Data Frame in the Standard Format always prevails over an Extended Frame.

IDE Bit – Identifier Extension Bit

The IDE Bit belongs to different Fields of the frame depending on the type of frame. In Standard Frames IDE bit belongs to the Control Field and is always dominant. In Extended Frames belong to the Arbitration Field and is always recessive. In case a standard remote frame is still competing for bus access with either a Data or Remote Frame in Extended format the arbitration is gained by the Standard Frame.

Control Field

The Control Field has different configurations for the different frames. In Standard Format Frames it includes the Data Length Code – DLC – , IDE Bit and the reserved r0 bit. Frames in the Extended Format include Data Length Code and two reserved bits r0 and r1 which must be sent as dominant but for future compatibility purposes the receivers shall accept them in all combinations. The Control field has a fixed size of 6 bits.

The Data Length Code indicates the length of the Data Field, is 4 bits long and may only take one of the following combinations:

Table 4 – Datal Length Code Combinations.

# Data Bytes DLC3 DLC2 DLC1 DLC0 0 d d d d 1 d d d r 2 d d r d

23

3 d d r r 4 d r d d 5 d r d r 6 d r r d 7 d r r r 8 r d d d

Although a Remote Frame does not carry any data on the Data Field it still provides a Data Length Code equal to the corresponding Data Frame with the same Identifier.

Data Field

On Data Frame exists a Data Field which is be carrying the number of data bytes specified in the Data Length Code of the Control Field. The Data Field may carry up to eight 8-bit bytes of data. The endianness within the Data Field is MSB first (Big-endian).

CRC Field

The CRC Field includes a CRC Sequence and a CRC Delimiter. The CRC Sequence is done according to BCH Code since it is the most suited for frames with less than 127 bits. The CRC Delimiter consists of a single recessive bit.

ACK Field

The ACK Field consists of 2 bits: The ACK Slot and the ACK Delimiter. The transmitting station sends two recessive bits and monitors the answer of the listening nodes. A receiver that correctly received the message acknowledges the same by sending a dominant bit during the ACK Slot. The ACK Delimiter must be a recessive bit and therefore a successful message should have its ACK Slot surrounded by two recessive bits: the CRC Delimiter and the ACK Delimiter.

End of Frame

All Data Frame and Remote Frame are delimited by a flag sequence consisting of seven recessive bits. This sequence is called End of Frame (EOF).

The previous description defines the contents of both Data and Remote Frames. The two special frames Error and Overload will be shortly explain below.

Error Frame

The Error Frame consists of two different fields. The first field is the superposition of the Error Flags

24

from all stations. The second field is the Error Delimiter.

Figure 7 – CAN Error frame.

CAN specifies two types of error flags: Active Error Flag (consisting of 6 consecutives dominant bits) and Passive Error Flag (consisting of 6 consecutive recessive bits).

When an Error Active node detects an error it signals this condition by send an Active Error Flag. Active Error flags either violate the bit stuffing law implemented in all fields of the frame or destroy the fixed form ACK Field or End of Frame. This way maintain the data consistency since all nodes will sense the error and discard the message received so far and also start sending an Error Flag. The total length of this sequence may vary from 6 bits to 12 bits. An Error Passive node tires to notify the error by sending a Passive Error Flag and considers the completion of the Passive Error Flag when monitor 6 bits of equal polarity.

The Error Delimiter consists of 8 recessive bits. After send the respective Error Flag each node keeps sending recessive bits until one recessive bit is monitored. When such happens it sends 7 more recessive bits.

Overload Frame

Overload Frames also include two fields: an Overload Flag and an Overload Delimiter.

Figure 8 – CAN Overload frame.

There are three kinds of conditions that may lead to the transmission of an Overload Flag:

25

• The internal conditions of a receiver which require a delay if the next frame.

• The detection of a dominant bit at the first and second bit of Intermission.

• If a CAN node detects a dominant bit at the last bit of an Error Delimiter or Overload Delimiter it will start transmitting an Overload Flag.

The Overload Flag consists of six dominant bits. The Overload Flag destroys the fixed form of the Intermission Field and as a consequence all nodes detect an overload condition and start transmitting an Overload Flag. However, if the dominant bit is detected during the third bit of Intermission it is considered a SoF. The Overload Delimiter is an 8 recessive bit signal and the process to start its transmission is the same that is used on the Error Delimiter.

Interframe Spacing

Both Data and Remote Frames are separated from preceding frames, whatever type they are, by a bit field called Interframe Space which contains the bit fields of Intermission and Bus Idle. It also contains the Suspend Transmission for Error Passive nodes which have been transmitter of the previous message.

Figure 9 – CAN Interframe Space – Error Active Node.

Figure 10 – CAN Interframe Space – Error Passive Node.

The Intermission consists of three recessive bits during which it is allowed to star an Overload Frame but not a Data or Remote Frame.

26

Bus Idle state is of arbitrary length and any node may send a SoF during this period.

Suspend Transmission is the eight recessive bit signal sent by an Error Passive node after transmitting a message, between Intermission and considering the bus to be in idle state. This is made to prevent Error Passive nodes (possible faulty nodes) with high priority messages to choke the bus.

2.4.2.3 Network Management

On matters of Network Management it is important to explain the fault confinement system implemented on CAN.

Status Classification

Each node may be classified as:

• Error Active

• Error Passive

• Bus Off

Error Active status is the normal status and any unit under this class may send an Active Error Flag (dominant) whenever an error is detected on the bus.

Error Passive nodes send Passive Error Flags (recessive) and must wait a minimum period of time after Intermission before start the transmission of a new message. This classification is given to nodes which are probably faulty or on faulty segments of the bus. Hence the errors in communication may be local and not affect the rest of the network and therefore there is no need to destroy communication consistency over the entire bus.

A Bus Off node may not take part on the network communication in matters of transmission and will most likely have its output drivers switched off.

In order to implement such node classification two error counters are implemented: Transmit Error Count and a Receive Error Count. There are numerous rules to increment and decrement the counters depending on the type of errors that are detected and the frequency of their occurrence. The status of each node changes when the counters exceed a certain quantity. If the counter passes 127 the node becomes Error Passive and if they reach 255 they become Bus Off. Since the rules allow for the counters to decrement it is possible that they become Error Passive or even Error Active again if a certain data consistency is monitored again.

Sleep mode and Wakeup condition

27

In order to minimize power consumption CAN also implements Sleep Mode and Wake-up conditions. The wake up conditions may be the detection of any activity on the bus or a special signal sent. The signal consists of a message with the lowest possible 11-bit Identifier: ‘rrr rrrd rrrr’ where ‘r’ stands for ‘recessive’ and ‘d’ for ‘dominant’. Since there is no single master system there is no use for a global Sleep Mode command.

28

Chapter 3

Main Board

3 Main Board

29

3.1 Chapter Overview

On this chapter the circuit synthesized for the main board of the application is explained. The main board is the hardware responsible for the communication with the on-board computer, the CAN clusters and LIN clusters.

3.2 Hardware

3.2.1 Overview

The microcontroller chosen, 18F4550 from Microchip, was selected regarding the output drivers and ports needed. However, the hardware for the TTL voltage level conversion necessary by each protocol is not included. The final board requires at least one transceiver for CAN, 1 transceiver for LIN and the standalone controller for the CAN driver. Other components such as coupling capacitors, voltage regulators and status LEDs are also contemplated here.

3.2.2 Microcontroller

The main board of the application was designed to be as low cost as possible. Although it would be expected to implement FlexRay, MOST, CAN, LIN and USB communication in a future version, the lack of documentation and hardware drivers for FlexRay, the cost of MOST interfaces as well as the lack of output for all of these protocols using a single MCU or DSP forced the final choices to be: CAN, LIN and USB interfaces.

As a world leader of MCU products, Microchip was selected as the provider for the microcontroller. It offers several solutions with multiple EUSART for LIN communication, CAN drivers for CAN communication and Hi-speed USB interfaces for USB communication.

Although other vendors such as and ST were considered, the lack of development tools and the cost of the led to the selection of Microchip as the MCU provider. However, for FlexRay and MOST implementation, another comparison should be made. The interface requirements for CAN and LIN are far inferior to the ones that are expected for these latter protocols and so is the operating frequency.

As the USB communication is the greatest restraint on the selection of the MCU, the selection of

30

models was firstly based on those who have an USB interface. However, there is no Microchip MCU that supports both USB and CAN interfaces. Microchip workaround was to create a standalone controller MCP2510 that could receive commands through a SPI interface and output it to the CAN bus. The MCP2510 was recently upgraded to its second generation version - MCP2515.

The MCU that was now sought should implement an USB interface, SPI port and a LIN compatible EUSART. Once again there was no MCU that had all these interfaces implemented in independent ways. All the available micro-controllers shared the SPI TX pin with the EUSART RX pin. The possible solutions considered were to either emulate a LIN compatible EUSART in software or to implement an intelligent use of the I/O port that was shared by SPI and the EUSART.

The hardware requirements led, in the end, to the choice of the microcontroller PIC18F4550 [9]. It includes an internal PLL that is able to produce a 96 MHz clock signal from a 4 MHz input needed for USB high-speed communication (12 Mbps), has a EUSART compatible with the LIN break signal and an SPI port for 10 Mbps communication.

The 18F4550 is high-performance, low power consumption device that comes in 40 or 44 pin packages. It has three 8-bit ports, one 7-bit port and one 4-bit wide port for multipurpose functionality although some pins are multiplexed with an alternate function from the peripheral features on the device. In general, when a peripheral is enabled, those pins may not be used as general purpose I/O pins. The microcontroller also supports three distinct 16-bit timers and one 8-bit timer that may be set up as counters and may have prescaler and postscaler features. Interrupts are also supported although only two priority levels (High and Low) are implemented. Flag-polling must be implemented in order to emulate greater priority hierarchy.

The microcontroller implements special circuitry that allows for PWM generation, serial communication using RS232, SPI, I 2C and USB protocols. Its general purpose ports may also be used for software emulation of such ports although the lack of dedicated registries may reduce significantly the transmission speed limits.

The packaging selected for this board was the 44 Lead QFN since is has the smallest dimensions. The pin diagram is presented in Figure 11.

31

Figure 11 – PIC18F4550 pin diagram.

3.2.2.1 Clock Configuration

The microcontroller supports USB communication at a maximum bit rate of 12 Mbps. The clock diagram inside the microcontroller requires special configuration, with particular attention to the 96 MHz PLL input that will provide the clock for the USB bit sampling and generation.

3.2.2.2 Port Conflicts

During the design of the protocol driver it was realised that the RX (input) pin of the EUSART used in LIN communication was also used as TX (output) pin in the SPI communication. Since the protocols were not used at the same time a protection circuit had to be designed in order to protect the port during output configuration (SPI communication).

32

Figure 12 – Port Conflict by shared node NX.

The circuit is presented in Figure 12. The MCP2515 represents the standalone controller for CAN bus communication and the MCP201 represents the transceiver for LIN bus coupling. There are two modes of operation:

• LIN bus communication

• CAN bus communication

In LIN bus communication the RC7/RX pin of the 18F4550 must be set to input since it is used as RX (receiver) for the LIN data bits. In this scenario the RC7 pin is an input connected to an output – RXD – on the transceiver and to another input – SI – on the standalone controller for CAN. This situation could lead to one potential problem:

• Data being misinterpreted in the MCP2515

However, since the SPI protocol requires a clock signal during the data transmission and the clock signal is turned off for LIN communication, the data on the MCP2515 will be ignored and no frame will be transmitted onto the CAN cluster.

In CAN bus communication the RC7/RX pin of the 18F4550 must be set to output since it is used as SDO (Serial Data Out) – an output pin – for SPI communication. In this case there is the possibility of an error:

• Both the RC7/RX (SDO) of the MCU and RXD pin of the LIN transceiver are trying to impose a

33

logic level on the node.

In order to eliminate this issue a resistive stage was installed in order to protect the outputs. Assuming that the system in working conditions behaves exactly as expected, the LIN bus should be on IDLE mode when the MCU is communicating with the CAN controller. IDLE mode in LIN bus is managed by setting the bus to the recessive state – High. For that matter, the output pin RXD of the LIN transceiver will be imposing 5V on the shared node. A resistive divider was installed between the two output pins, having its output node connected to the MCP2515 SI pin. According to the DC characteristics of the MCP2515 the values for VIH and VIL for the SI pin are the following:

Table 5 – VI for MCP2515 pin SI and VO for PIC18F4550 pin RC7.

MIN MAX Units VIH (SI) 0.7 VDD VDD + 1 V VIL (SI) -0.3 0.4 V VOH (RC7) VDD – 0.7 - V VOL (RC7) - 0.6 V

Taking the provided information, the relation between both resistors had to be such that when the RC7/RX pin tries to impose 0V on the shared node, the value at the MCP2515 would be within the allowed voltage levels.

In order o obtain a low value of 0.3 V at the SI pin the ratio between the two resistors must be 15.66:

V R1 High ⋅=R2 0.3 V ⇔ = 15.66 (1) R1+ R 2 R 2

Hence, the chosen values for the resistors were 15 kΩ for R1 and 1 kΩ for R2.

The output protection stage is represented on Figure 13.

NX

Figure 13 – Port Conflict workaround for the shared node NX.

34

During the CAN operation RC7 imposes the voltage level on the node NX. Since RXD is 5 V on idle state, if the RC7 is set to High the value on the node will be High, if RC7 is set to Low the voltage on SI will be the direct result of the voltage division and around 0.3 V. When the LIN bus is not idle then LIN mode is enabled and both RC7/RX and SI pins are set as inputs allowing any voltage level to be set on node NX.

3.2.3 Transceivers

Both CAN and LIN buses require coupling to the data buses. The microcontroller outputs TTL levels and therefore dedicated transceivers are required. The Microchip solutions for the two cases are the MCP2551 for CAN and the MCP201 for LIN.

3.2.3.1 MCP2551

Figure 14 – MCP2551 block diagram.

The transceiver has eight pins [10]:

• VDD and VSS used for input of power supply and ground

• TXD and RXD to connect to the CAN controller MCP2515.

• Vref - output of reference voltage defined as VDD/2.

• CANH and CANL for connection to the CAN Bus.

• Rs input for EMI control. Rs pin allows for precise control over the transceiver’s slew rate. In HS mode Rs is supposed to be directly connected to VSS reducing the transition time between logic values transmitted onto the CANH and CANL bus. Other configurations, contemplating resistors up to 120 kΩ, are able to reduce the slew rate from 24 V/ µs down to

35

4 V/ µs (Figure 15).

On the TX circuitry, as CAN protocol requires a 2-wire differential medium, the conversion from the TTL logic levels to CANH and CANL signals is done by a driver that controls two transistors connected to either pull-up or pull-down resistors. On idle mode the transistors are OFF and the CANH and CANL are imposed by the bus.

On RX circuitry, the values of CANH and CANL are compared and the result of the exclusive OR is outputted to the RXD pin. If the voltage is different between both pins – CANH and CANL – a TTL High is detected, if the voltage is the same a TTL Low is detected.

Figure 15 – Slew Rate characteristic as function of Rs resistance.

3.2.3.2 MCP201

This transceiver [11], designed for low cost LIN nodes includes a voltage regulator that is intended to supply power to the controlling unit.

The transceiver has 8 pins:

• RXD and TXD for controller interface.

• Vss and Vbat for power supply purposes.

• Vreg - output of 5 V power supply for MCU up to 50 mA.

• CS/Wake to select the operation mode of the transceiver.

• LIN for LIN bus interface.

• Fault/SLPS – Used mostly for fault detection as an output. While as input allows the selection of normal slew rate mode (2 V/ µs) if connected to Vreg (5 V) or the 4 V/ µs slew rate if connected to ground. However, the 4 V/ µs slope mode is not LIN compliant but may be used for K-line applications. Slope Control mode is entered during power-up of VBat.

36

Figure 16 – MCP201 Block Diagram.

In the TX circuitry, the TX pin has an internal pull-up resistor to Vreg setting the bus at High (recessive) state. When TXD is low, the LIN pin is in Low (dominant) state. If the Thermal Protection module detects an over temperature while the transmitter is imposing the dominant state, the transmitter is turned off until a normal temperature level is detected.

The RX circuitry is a standard CMOS output stage and follows the state of the LIN pin. The RXD pin is internally connected to Wake-up logic to provide built-in wake-up functionality.

Figure 17 – MCP201 Typical Circuit.

As the master node of the LIN bus will be nested in the main board, special bus coupling must be taken into account. The suggested typical application for LIN nodes is the circuit above.

On the master node a pull-up resistor and protection diode are needed in order to force an Idle recessive state. Also the optional diode D2 may be inserted for transient suppression. The optional components at (5) are for load dump protection and the D1 diode is supposed to be used only if CS/WAKE is connected to a 12 V supply.

37

In order to enter operating mode, a sequence of pulses must be sent to the CS/WAKE pin. A sequence of False  True  False  True will result in Operating Mode independently of the previous mode. Each mode requires a wait interval of 600 µs as the regulator powers its internal circuitry which equals 3000 clock cycles in a MCU with a 20 MHz crystal.

Figure 18 – MCP201 State Machine.

3.2.4 CAN Controller

The MCP2515 [12] is the standalone controller that implements receive and transmit buffers, masks for message ID filtering, driver rules for arbitration, driver rules for frame interpretation and driver rules for frame generation. It has 18 pins, most of them for output of internal conditions and bus status. The controller requires a dedicated oscillator in order to be able to define a precise bit time. It also has 4 dedicated pins to serial communication and 2 pins dedicated to transceiver interface.

Figure 19 – MCP2515 Block Diagram.

38

The function of the pins are as follows.

• VDD and VSS – power supply pins.

• OSC1 and OSC2 – External Oscillator input and output.

• TXCAN and RXCAN – Input and Output for communication with the CAN transceiver.

• SCK, SI, SO, CS – SPI interface pins.

• INT – generic interruption pin.

• RX0BF and RX1BF – RX0 and RX1 Buffer Full Interruption pin.

• CLKOUT/SOF – Clock output with programmable prescaler / Star of Frame Signal.

• TXnRTS – Transmit Buffer n Request-to-Send input / General Purpose Digital Input.

• RESET – Active low device reset input.

The controller accepts HS SPI commands up to 10 MHz in either mode “0,0” or “1,1”. Since there is no interface for software programmers such ICD2, all configuration of the message ID filtering, general purpose pins functionality and active operating mode must be configured through the SPI interface.

The controller can be found in five distinct modes:

• Configuration mode – Prior to activation the registers, filters and other functionality must be set. Configuration mode allows the SPI interface to address special registers that define the behaviour of the controller just as the bit rate of the CAN bus and the interruptions to be associated with the general purpose pins.

• Normal mode – This is the normal mode of operation and should be selected once the entire configuration has been done. During this mode the CAN bus is being monitored for incoming communication and it is the only mode in which the MCP2515 will transmit messages over the CAN bus.

• Sleep Mode – A power saving mode where some functionality is disabled if not needed, including the external oscillator. However, the SPI and CAN interfaces are still active in order to wake up upon SPI wake command or CAN bus activity.

• Listen-only mode – Similar to Normal mode but with the transmitter disconnected. Listen-only mode is useful for bus monitoring or bit rate detection in ‘hot plugging’ situations.

• Loopback mode – This mode is used to allow transmission of messages from the transmit buffer directly to the receive buffers without actually sending them to the bus. This mode is

39

intended for testing and developing only.

The CAN protocol uses a Non Return to Zero encoding which does not encode a clock within the data stream, therefore the receiver’s clock must be configured by the receiving nodes and synchronized to the transmitter’s clock. For accurate detection, the receiver must implement some kind of PLL synchronized to data transmission edges, in order to synchronize and maintain the receiver’s clock. The CAN protocol includes bit stuffing to ensure that an edge occurs at least every 6 bit times to maintain the Digital PLL synching.

CAN defines the most elementary time unit as Time Quanta – TQ – and the Nominal Bit Rate (NBR) as the number of bits per second transmitted by an ideal transmitter without resynchronization. The NBR is made up of non-overlapping segments each made up of several TQ and can be described as (Figure 20):

tbit =t Synch + t Pr op + t PS 1 + t PS 2 (2)

tSynch (Synchronization Segment) – Represents the time taken for the nodes to synchronize on the bus. The length of the Synchronization Segment is 1 TQ.

tProp (Propagation Segment) – Represents the time spent to compensate the different nodes physical delays. The propagation delay is defined as twice the sum of the signal’s propagation time on the bus line. This segment is programmable in MCP2515 form 1 up to 8 TQ.

tPS1 and tPS2 (Phase Segment 1 and 2) – This segments are used to compensate for edge phase errors on the bus. PS1 is programmable from 1 to 8 TQ and PS2 from 2 to 8 TQ.

Figure 20 – CAN Nominal Bit Time Segments.

The sample point indicated in the diagram represents the point at which the transmitted bit is being sampled for message interpretation purpose. The sample point is located at the end of Phase Segment 1 except if the controller is configured to execute triple sampling in order to increase accuracy.

In order to configure correct timing rules the time length of the TQ must be determined. TQ depends on the oscillator period and on the Baud Rate Prescaler (BRP) selected. Equation (3) describes the TQ time length.

40

TQ =2 ⋅ BRP ⋅TOSC (3)

Where BRP represents the integer programmed into the BRP register and Tosc represents the period defined by the external oscillator.

In order to program the time segments some rules must be taken into account:

• Prop. Seg. + Phase Seg. 1 >= Phase Seg. 2

• Prop. Seg + Phase Seg. 1 >= Tdelay

• Phase Seg. 2 > Synch Jump Width

Where Tdelay is typically 1-2 TQ and Synch Jump Width (SJW) is a value between 1 and 4 TQ used to adjust the bit clock to maintain synchronization with the transmitted message. Typically high SJW values are only required in clusters where nodes have poor clock generation such as when using ceramic resonators. A SJW of 1 is usually sufficient.

For this particular case there are various possible configurations for the TQ distribution within each segment. Considering a bus bit rate of 1 Mbps, the number of TQ that a single bit time comprises is

tBit tBit =X ⋅TQ ⇔ TQ = , with (4) X

1 tBit = = 1 µs Bitrate . (5)

Now taking into consideration a crystal of 20 MHz with a period of

1 Tosc = = 50 ns , (6) fosc and considering equation 3 and 6, the TQ can be expressed as:

TQ=0.1 µ s ⋅ BRP . (7)

Making use of equation 4, 5 and 7, a relation between the amount of TQ per bit time (X) and the BRP value is obtained:

tBit 1 µs TQ== =0.1 µs ⋅ BRP⇒ 10 = XBRP ⋅ (8) X X

This allows for two values of BRP: 1 and 2, since no other value will result in an integer X.

The following table summarizes the possible value and distributions of TQ per segment for this

41

specific case taking into account that the sampling time must occur at about 60-70% of the nominal bit time. With these specifications there are only 4 possible scenarios:

Table 6 – CAN Time Quanta Distribution.

Bit time BRP=2 BRP = 1 Scenario 1 Scenario 2 Scenario 3 Scenario 4 0 - 0.1 Bit Time 0.1 - 0.2 Bit Time 0.2 - 0.3 Bit Time 0.3 - 0.4 Bit Time 0.4 - 0.5 Bit Time 0.5 - 0.6 Bit Time 0.6 - 0.7 Bit Time 0.7 - 0.8 Bit Time 0.8 - 0.9 Bit Time 0.9 - 1 Bit Time Legend:

Synch Segment Propagation Segment Phase Segment 1 Phase Segm ent 2

Since it will be used a 20 MHz crystal as the controller clock, there is enough precision to selected a BRP equal to 1 and chose a scenario from the last three. The most balanced scenario of all three – Scenario 3 – will be selected since the conditions of the bus are yet unknown. For further tuning in case of bad transmission, adjustments may be made later.

The final configuration must be:

• BRP = 1

• Propagation Segment #TQ = 2

• Phase Segment 1 #TQ = 4

• Phase Segment 2 #TQ = 3

Interruption Handling

In order to minimize the queries to the controller, the RXnBF pins provide a comfortable way to detect an incoming message. As soon as the RX buffer receives a message, an interruption may be triggered (if previously configured for that effect) and inform the MCU that there is new information to be fetched.

42

On this application the RXnBF for buffers 0 and 1 will be activated and connected to general purpose I/O pin on the MCU.

3.2.5 Status LEDs

The main board of the application will have a visual output of its internal state defined by four status LEDs. The first two leds – LED 1 and LED 2 – will be used for USB interface diagnostic and the blinking code is the same as the defined by Microchip USB driver for the 18F4550 USB interface.

Table 7 – Led Blinking Code.

USB status LED1 LED2 Suspended State Toggle Equal to LED1 Detached State OFF OFF Attached State ON ON Powered State ON OFF Default State OFF ON Address State Toggle OFF

Configured State Toggle Opposed to LED1

3.2.6 External Connectors

The main board requires several connectors to interact with three different buses, for future testing and debugging and for firmware updates with the ICD2.

Although there is not strict connector imposed to be used on CAN and LIN bus, the most common are the same D9 connectors used in other serial communication protocols such as RS232. As the type of connector used does not impose restrictions on the type of connectors that are to be used by the other nodes, on this board the interfaces will be implemented with RJ connectors for size reduction purposes, except for the USB interface.

• CAN and LIN will use a RJ10 female connector since they only require up to four optional pins.

• ICD2 will use a RJ12 female connector since this is the default connector used by Microchip programmer: ICD2.

• USB will use a female USB type-B connector, used mostly on peripheral devices such as the main board.

43

3.2.7 Power Supply

The Main Board requires a power supply of 200 mA and 5 V. Since the power must be obtained from the car battery and this is always above 6 V and is supposed to be usually between 11.5 V and 13 V, the converted needed is a buck or step-down DC-DC converter. Ordinary power regulators such as 7805 have very high power dissipation due to the internal configuration. They are designed to dissipate the remaining voltage and as the input voltage tends to be greater, the power consumption is even bigger.

The chosen converter was the LT1776 [13] since this buck is a low power consumption regulator. The block diagram shows the internal oscillator, the control circuitry used to generate the PWM signal that controls the switch and the protection circuitry all in a monolithic die. This device also supports input voltages up to 60V, far higher that ordinary power regulators.

The LT1776 is supposed to be assembled in a configuration similar to the one depicted in Figure 21, making this the layout chosen for the power supply of the Main Board.

Figure 21 – LT1776 Typical Application.

3.2.8 Summary

In this chapter, all of the hardware for the main board was specified. All the expected conflicts were resolved and the hardware references for the MCU, CAN controller, transceivers and connectors were given. Also the functioning of each transceiver and controller was explained to a certain detail to allow for better system design and configuration.

The final schematic of the complete board can be found as Annex 2.

44

3.3 Software

3.3.1 Introduction

The software for the microcontroller may be roughly divided into four sections:

• System Configuration

• LIN communication

• USB communication

• CAN communication

Each one of these four sections will be approached individually and have its own flowchart whenever one is found to be essential for algorithm understanding.

3.3.2 System configuration

The microcontroller firmware flowchart can be summarized to the diagram in Figure 22.

Figure 22 – Flowchart of the Main Routine: main.

The first routine to be called is the InitializeSystem(). This process is responsible for setting the OSCCON register to the correct value so that the external oscillator may be correctly configured, enable interrupts and interrupt priorities, sets the correct direction for the general purpose bidirectional I/O ports and calls each bus specific initialization routine. Since CAN bus and LIN bus are optional buses and may or may not be activated, dedicated pins on the microcontroller are used to enable these buses. The initialization routines will be only called in case these pins are set to High.

The main function then enters an infinite loop where:

• The WatchDog timer is cleared, ClrWdt().

45

• The USB status is checked and its output LEDs are set accordingly, USBTasks().

• The USB I/O checks for incoming communication from the On-board computer, ProcessIO().

• CAN and Lin buses are finally assisted, LinCOM() and CanCOM().

Once again the CAN and Lin buses are only accessed if the activation flags (dedicated pins on the MCU) are set to 1.

Although the flowchart may suggest that the bus querying mode is based on polling, some aspects rely on the fast response of the interrupts architecture. The Interruption Service Routine (ISR) will assist any incoming data on the RX pin in order to implement the LIN driver.

3.3.3 LIN Communication

Start

If sucessful Transfer

Yes

If Error on Set Error Led Yes Response Timer

No

Yes

No If USB is Busy

No

Send Data bytes and frame info through USB interface

Return

Figure 23 – Flowchart of the LIN polling routine: LinCOM.

Although LIN is a popular protocol, there are very few implementations of a complete LIN 2.0 driver. Application Notes AN1099 from Microchip implements a complete driver for the MCU families PIC18XXXX. The driver had to be adapted not only for the MCU used, but also for compatibility with the dynamic schedule-table structure engineered for this particular project.

46

The flowchart of the LIN communication routines is divided in 2 parts: the polling routine (for process of successful received messages) and the interruption routine (for communication with the other nodes).

As for the interruption service routine, since the LIN driver is fully implemented in software unlike the driver for CAN used on this project, all of the stages of transmission are contemplated. In order to keep the flowchart organized most of the actions were summarized to a key description.

The driver assumes that the master node may be in 6 different modes:

• SynchBreak: Waiting for a SynchBreak (Break) character consisting of at least 13 Low bits. This data configuration flags the framing error bit on the RCSTA register of the MCU and is the only time that the data is taken into consideration after detecting an error.

• SynchByte: After the SynchBreak character, the master sends a Synch character for baud rate detection purposes on slave nodes. The Synch character has the hexadecimal code 0x55 in order to maximize the transitions between logical levels.

• IdentifierMode: After the SynchByte mode the master sends the identifier byte of the scheduled message. The identifier has only 6 effective bits being the last 2 for parity check. If the master detects a valid identifier it processes the associated header and determines whether to set Xmit/Receive mode or to set SynchBrake mode.

• ReceiveMode: While on ReceiveMode the master is supposed to accept all incoming bytes and according to the length of the expected message verify the CRC byte. In case of a successful reception the successful reception flag is set.

• Xmit: While on Xmit mode the master keeps transmitting the data bytes stored in the source buffer. It compares the sent byte with the received byte since the RXIE has been disabled. In case of success the master sets the successful transfer flag. In case of error, the transmission error flag.

• Sleep: while on sleep mode the master only monitors a wakeup signal. In case of a successful wakeup signal is detected it starts the EUSART and sets the baud rate register SPBRG.

The driver uses two flag bytes: an error flag – errorflags_u – for error details; a status flag – _ifc_status – for transmission status. Whenever a flag is set in the flowchart (Figure 24) it refers to either one of these flags being it the first for error notification purposes or the second for transmission status.

47

Start

If TXIF AND mode = Disable TX interruption Yes SynchBreak Enable RX interruption

No

If Timeout = Enabled Yes Set Timeout Error AND TMR0IF = 1

No

If RCIF=1 No End

Yes

If OverRun=1 Yes Restart Receiver

May be SynchBreak character: No 13 Low bits create a framing error

If frame Clear Error Flag If Timeout = Start Timeout Yes If data=0 Yes Yes corrupted Set mode = SynchByte Enabled Timer

No No No

mode = Add received data to Send 0x55 Yes Add CRC byte ReceiveMode destination buffer (SynchByte)

End

If last byte No

Yes

No Set CRC Start Idle State Timer If CRC error Yes error Flag Set mode = SynchBreak

No

Set Sucessful Transfer Flags

Figure 24 – Flowchart for the LIN driver part 1.

48

Figure 25 – Flowchart of the LIN driver part 2.

49

3.3.4 USB communication

The USB driver used on this project is a modified version of the provided driver by Microchip™ on their demonstration board PICDEM USB. It is configured as a polling driver that keeps checking for newly received data frames. The polling routine is the one mentioned on the main routine: ProcessIO().

The driver loads a structure of 64 bytes with the received data named DataPacket. This structure had to be modified to be compatible with the protocol developed for this project. The protocol develop will be reference as to MBP – Multi Bus Protocol.

Figure 26 – MBP data frame.

The new structure on the DataPacket is the one in Table 8.

Table 8 – MBP Fields Description.

Sta rt # of bytes Name Description 0 1 Type Descriptor of the type of message. 1 1 BUS Identify which bus the message is intended to be sent to. 2 1 PORT For future usage, in case multiple ports of the same bus are implemented. For instance two CAN interfac es. 3 4 DeviceID_MAJ For device identification, Vendor ID for instance. 7 4 DeviceID_MIN For device identification, Product ID for instance. 11 4 InstructionID Instruction ID used for the destination protocol bus. 15 2 length Length in bytes of the dat a field.

17 39 _data Data Field. May only contain part of the data do be transmitted. The length of the valid data on this field is 56 8 reserved Reserved for future upgrades on the protocol.

The field Type of the designed protocol supports the following values:

Table 9 – Type Field values.

Type Hex Description MSG_ERROR_ID 0x30 The data field carries information on an error that occurred. MSG_WARN_ID 0x31 The data field carries a report o f possible fault.

50

MSG_REQ_ID 0x32 The data field carries a request to the specified bus, a response is supposed to be received from another node. MSG_RESP_ID 0x33 The data field carries a response from another node to a request made previously. MSG_SPORADIC_ID 0x34 The data field carries a sporadic data frame sent by another node MSG_MULTIRESP_ID 0x35 The data field carries messages that were fetched from a bus but are not direct answers or requests to the master MSG_ORDER_ID 0x36 The data field carries a message that does not require response from another node.

The USB communication routine is the trigger for the new transmissions issued by the master in all of the remaining buses. When a MSG_REQ_ID or MSG_ORDER_ID arrives, the master gets ready to process the new transmission.

Although LIN protocol implies the usage of a schedule table on the master task, the table may be dynamic and in this particular case it is created on-the-fly. As soon as an USB message arrives containing a data frame to be transmitted onto the LIN bus, the master creates a single-task schedule table and starts transmission. The same procedure is used for CAN data frames. However, CAN does not use a single master architecture, hence the need to check for bus status before attempt to send the frame.

If and error is detected the master should report to the on-board computer with an MSG_ERROR_ID or MSG_WARN_ID in case the fault was not critical. If a transmission is successful and a response arrives the master notifies the on-board computer with a MSG_RESP_ID. If a node, for instance in the CAN bus, requests data from the master this should report to the On-board computer with a MSG_SPORADIC_ID.

The role of this master task is mainly to create a hardware bridge between the application running on the On-board computer and the various buses implemented. All the data processing should take place on the On-board computer.

The BUS field may carry any of the following identifiers. If new versions of the respective protocols are release new identifiers should be created to avoid ambiguity. The current firmware release considers protocols that were not implemented but are plausible of serious consideration.

Table 10 – Bus Field Values.

BUS Hex Description BUS_SYS_ID 0x70 System BUS_USB_ID 0x71 Universal

51

BUS_LIN_ID 0x73 Local BUS_CAN2B_ID 0x72 Controller BUS_MOST_ID 0x74 Media BUS_F LEXRAY_ID 0x75 FlexRay BUS_OBD0_ID 0x76 On Board BUS_OBD1_ID 0x77 On Board BUS_OBD2_ID 0x78 On Board BUS_LIN11_ID 0x79 Local BUS_LIN12_ID 0x80 Local BUS _LIN13_ID 0x81 Local BUS_CAN1_ID 0x82 Controller BUS_CAN2A_ID 0x83 Controller

The PORT field should be 1 in the current firmware release. For future boards where more than a single interface for the same bus is available, PORT will decide which should be addressed.

DeviceID fields are used differently upon the destination bus. For LIN they are supposed to be used for the certified Vendor ID and respective Product ID.

IDENTIFIER field is supposed to carry the PID for LIN and Message Identifier for CAN. It is mandatory for all communications.

LENGTH specifies the length of the data field in bytes. It may range from 0 to 65535. If more than 39 bytes of data are supposed to be transmitted, the following data bytes must arrive in the following data packets. The protocol does not standardize the format for multi data packets frames. If some control mechanism just as ACK or packet order is to be implemented, it is up to the use to define the best method to its application.

_DATA field carries the data bytes to be sent on the frame. Byte endianess is not specified for messages with more than 39 data bytes. For messages with less than 39 data bytes the transmission should be FIFO, first byte to arrive is the first byte to be dispatched. It is up to the on-board computer to send the correct byte endianess regarding the protocol that is being used.

RESERVED bytes are supposed to be used for future upgrades to the protocol and should not be used in this version.

3.3.5 CAN communication

CAN communication has no software driver implementation in this firmware version. The device used for the driver – MCP2515 – was already explained. The MCP2515 uses the SPI interface to communicate with the MCU and requires a dedicated crystal for Time Quanta generation.

52

The driver has the SPI port configured to run at 5 MHz and requires configuration information from the MCU. Although the MCP2515 was already explained in the previous sections, in this section the configuration registers and its loaded values will be explained.

The MCP2515 needs to be set to configuration mode for special registers access, namely for the ones responsible for the amount of TQ available to each of the nominal bit time segments.

The configuration routine starts with a reset command, hexadecimal code 0xC0. The reset command sets the register values to the Power-On Reset. The following command sets the controller to configuration mode by acting upon the CANCTRL register. On configuration mode access to CNF1, CNF2, CNF3 and filtering registers is gained.

CNF1 register defines the length of Synchronization Jump Width – SJW – and the baud rate prescaler. The SJW is required for unreliable oscillators with poor accuracy and in this particular project may be set to its minimum: 1 TQ. The baud rate prescaler is used to define the length of the TQ as a multiple of the oscillator period. On this particular project

TQ=⋅2 T osc = 0.1 µ s (9)

The number of TQ available for each segment was already defined on Chapter 4. On CNF2 the length in TQ of the Propagation Segment and the Phase Segment 1 are set. On this register it is also specified if the bit will be sampled only once at the sampling point or if it will be sampled three times with TQ/2 decrements up to that point.

The CNF3 specifies the length in TQ of Phase Segment 2, the state of the wakeup filter and the function of the clockout pin, which can be either signalling the SoF or output a clock signal. In this particular project, the clockout pin will output a clock signal at a 5 MHz for debugging purposes. In order to make sure that the controller is configured in the correct way, a 5 MHz square wave form should be being output through clockout pin.

Detailed information about the register bits is on Annex 3.

After configuring the bit timing, the interruptions generation must be customized in order to be able to monitor interrupts whenever a message arrive instead of keep polling the controller. The registers responsible for interruption configuration are: BFPCTRL, CANINTE and CANINTF.

The CANINTE enables the interruptions that will trigger the generic INT pin. This pin will be only used for error detection while the BFPCTRL register configures the RXnBF pins as interrupt pins for successfully received messages.

The filtering registers for messaging are set to fully permissive since the main board is supposed to be able to accept all types of frames. The registers responsible for that task are:

• RXBnCTRL for the accepted identifiers (extended or standard)

53

• RXMnSIDH and RXMnSIDL for the mask bits

• RXFnSIDH and RXFnSIDL for the filter bits

The last step in controller configuration is to set the MCP2515 back to normal mode and start monitoring the interruption pins for incoming messages. This step involves changing the CANCTRL register again.

The access to these registers, in order to write the desired values, may be done from two different ways: Register Write Command or Register Modify Command.

The Register Write Command consists on sending the character with the hexadecimal code 0x02 followed by the register address hexadecimal code and then followed by the value to be loaded on that register. For instance, for CANCTRL, to load the value defined above (0x0E) we would send to the SPI interface the following sequence:

0x02; 0x0F (CANCTRL address); 0x0E (value to be stored).

As for the other command: Register Modify Command, the hexadecimal code of the command is 0x05. After sending the command the address of the register must be sent and only then a byte with the mask for the filter. The value to be loaded is the fourth character to be sent and the mask rules apply as follow:

REGISTER = (REGISTER || (MASK && VALUE))

Only the bits that were set in MASK will take the value of the correspondent bit of VALUE. Also this value will be submitted to a bitwise OR with the actual value of the REGISTER. So assuming that the POR value of CANCTRL was 0x01 the sequence to set it to the desired value would be:

0x05; 0x0F (ADDRESS); 0x0F (MASK); 0x0D (VALUE).

54

Chapter 4

On-board Computer

4 On-board Computer

55

4.1 Chapter Overview

On this chapter the on-board computer will be analysed. Decisions will be made towards the best machine to host the application as well as the application itself.

4.2 Hardware

The environment inside the automobile is problematic. The temperatures may vary from -40ºC to 90ºC depending on the geographic location and proximity to the engine. Also, the electric current and voltage level provided by the battery may oscillate depending on the number of devices using the power supply such as headlights, start-up engine and the sound system amplification among others. The mechanical impact of the road conditions and driving skills also imply certain restraints to the On- board Computer components such as the mobility of the needles in magnetic storage devices. Taking all this factors in consideration the system sought for good performance would be a real time computer, running a light kernel operating system and with a Flash memory card as a HDD.

As the system is supposed to be suspended during the period of time when the automobile is not working and have a fast wake-up when the automobile is turned on, the hardware selected should be able to run and embedded operating system with a few seconds maximum reboot time such as Windows CE or Embedded Linux. Also the system should provide USB ports for communication with the main board and a touch screen for driver interface. The power supply should be oriented for low power consumption and have high tolerance for the battery transients.

4.2.1 Processor and screen

4.2.1.1 Ideal Processor

During the past 5 years several solutions were developed for On-board devices, however the perfect solution still resides in two different markets, Personal Digital Assistants (PDA) for the processor and peripheral support and automotive for power supplies. The On-board computers for the latest automotive solutions are still too primitive regarding the latest processors for mobile applications. When looking for a processor for an On-board Computer the best solutions are found among cellular phones and PDAs. These have already built-in support for USB and wireless communication, boot from flash storage devices and have extremely low power consumption allowing the suspended state

56

for several days on 800mAh battery. Also most of the displays are touch-screen and the dimensions are extremely small. On the other hand, power supplies for these devices are steady. There is no real concern with the voltage transients and current loss due to sudden peripheral action. Another concern with the power supply has to do with the possibility to feed peripherals. On-Board Computers may have to power up devices that require great amounts of energy such as 10 inches touch screen LCDs or speakers.

As for the processor, the latest product from Intel – PXA270/1/2 – seems to be the perfect solution. This new processor supports temperature ranges from -40ºC to 85ºC, may run up to 624 MHz, has MMX wireless technology support, has up to five different built-in low power consumption modes, 2 USB interfaces including USB On-The-Go, MMC/SD card/Memory Stick support, 4 SD I/O, USIM card interface and supports RAM ranging from 1.8 V up to 3.3 V. The processor is based on a fifth generation ARM and a complete system runs with less than 12 W. The problems found with this processor that made it unable to be implemented on the project were two:

• Development kits cost from €1500 up to €3000 as of the writing of this paper.

• Although similar to standard Microsoft Windows XP, the coding necessary for compatibility with Windows CE would take at least 3 to 4 weeks.

4.2.1.2 Ideal Display

The best display that could be used in this application would be 8 to 10 inches touch screen display, if possible in OLED technology [14]. However, OLED technology is still considered experimental for larger applications and a touch screen with a dimension greater that 4 inches is either unavailable or extremely expensive. OLED displays provide a contrast ten times greater than normal LCD, has extremely low power consumption since do not require backlight and are supposed to be rather thin and temperature tolerant. Recent Sony OLED products are 3 mm thick and 10 inches wide.

4.2.1.3 Cost-effective, Low-Power Processors and Displays

Since the ideal platform could not be used, other devices were compared regarding power consumption as the main feature of concern. In cases where the differences between the power consumption are irrelevant or the models were not available, two more figures of merit were used:

• CPU_MHz / Watt

• (CPU_MHz * RAM_MHz) / Watt

There are two major companies devoted to low power X86 processor design: VIA and Intel. However, VIA has a larger catalogue on this area and has been the main supplier for Car-Computer systems in the last years. A comparison based on the available models from VIA was made and the figures of

57

merit calculated.

Table 11 – VIA processor comparison table.

CPU RAM Max CPU_MHZ / (CPU_MHz * RAM_MHz) / Processor MHz MHz Power Watt Watt

Via C7 2000 800 20 100,00 80000,00 Via C7 -M 1800 400 18 100,00 40000,00 Via C7 -M 2000 400 20 100,00 40000,00 Via C7 -M 1600 400 15 106,67 42666,67 VIA Eden 600 400 5 120,00 48000,00 Via C7 1800 533 15 120,00 63960,00 Via C7 1500 533 12 125,00 66625,00 Via C7 -M 1500 400 12 125,00 50000,00 VIA Eden 500 400 3,5 142,86 57142,86 VIA Eden 400 400 2,5 160,00 64000,00 VIA Eden 800 400 5 160,00 64000,00 VIA Eden 1200 400 7 171,43 68571,43 VIA E den 1000 400 5 200,00 80000,00 VIA Eden ULV 1500 400 7,5 200,00 80000,00 Via C7 -M ULV (770) 1000 400 5 200,00 80000,00 Via C7 -M ULV 1500 400 7,5 200,00 80000,00 Via C7 -M ULV 1200 400 5 240,00 96000,00 VIA Eden ULV 1000 400 3,5 285,71 114285,71 Via C7 -M ULV (779) 1000 400 3,5 285,71 114285,71 VIA Eden ULV 500 400 1 500,00 200000,00

Through basic analysis of the table above it is possible to verify that VIA EDEN [15] processors have the best ratio CPU clock / Maximum power consumption. Excluding the ULV (Ultra Low Voltage) versions, which are extremely hard to find, the best option would be a VIA EDEN 1.0GHz with 400 MHz FSB for RAM communication. This processor has a ratio of CPU Clock * RAM FSB / Watt equivalent to the 2.0GHz C7 computer, a state-of-the art processor. However, VIA EDEN 1.0GHz is not sold with passive cooling in ITX form factor and a fan is extremely undesired in a car computer since it means more power consumption and mechanical-intolerant systems. The only VIA EDEN 1.0GHz fanless distribution had a nano ITX form factor and was twice as expensive as the VIA EDEN 1.2GHz.

The chosen processor was the second on the list, the 1.2 GHz VIA EDEN which was distributed with passive cooling on an ITX motherboard. Although there is an increase of 2 W in the processor power consumption, there is also an increase in Clock speed and the safety of a passive cooling system.

58

Figure 27 – VIA EDEN Processor.

As for display, since the display will only be turned on during the time when the engine is running, the power consumption is not the greatest concern. One of the sponsors of the thesis provided a 10 inches display with VGA input and RS232 connector for touch-screen functionality. It was the display used on the prototype.

4.2.2 Power supply

The power supply for automotive applications is already extremely reliable. The main suppliers in the automotive industry are Oppus and Morex. Prices range from €30 to €80 and reflect the functionality of the power supply. Most low cost powers supplies do not provide the connector for ITX motherboards or the voltage tolerance that is expected.

M2-ATX-HV is a 140 W, 6 V to 32 V wide input DC-DC power supply. It has intelligent detection of ignition allowing for special commands to the motherboard ON/OFF switch, is prepared for engine cranks and fits in most popular SBC form-factor PC enclosures. Another extremely useful functionality is the battery monitor. M2-ATX constantly checks the battery level and if it crosses safety limits M2- ATX does a full shutdown until secure levels are reached again.

As for outputs M2 comes with ATX, HDD and Floppy cable harness and 2 pin cables for motherboard ON/OFF switch.

Another logistic advantage is that M2-ATX may be bought in Europe unlike most other solutions.

Figure 28 – M2-ATX power supply.

59

4.3 Software

4.3.1 Introduction

The software for the On-board Computer was divided into three sections:

• Operating System

• Graphical User Interface

• Application Kernel

As for the list items 2 and 3 two different languages where chosen: C++ and HTML/JScript.

The application layer consisted of an USB interface (for Main Board communication), Multi Bus Protocol driver (for command processing) and a graphical interface (for the vehicle driver). Once again the new trends were analysed and a web interface was chosen. Some renowned companies such as Symantec or Hewlett Packard started using web interfaces for end-user input and output. The reason has to do with shorter developing time and compatibility with web services. As for USB communication, C++ was a comfortable choice since the Microchip driver for the USB device is written in C++. Also C++ has all the advantages of C programming plus support for objects and garbage collection features. The communication between the C++ USB driver and the web interface is done with ActiveX technology.

4.3.1.1 ActiveX

In order to integrate C++ modules with the user interface, a third interface mechanism was needed. The chosen technique was an ActiveX interface. ActiveX interface allows for the C++ module to be accessed from an HTA, VBA or even a webpage, meaning that multiple interfaces could be developed regardless of the language used in the core module. ActiveX is another name for Object Linking and Embedded Automation and is mostly used for reusable objected oriented software components such has the one developed in C++.

4.3.1.2 HTA – Web Interface

The HTA is the Microsoft answer for HTML-based trusted applications. It consists on a trusted application with permissions to manipulate the file system structure or even system registry. In HTA, HTML is used for layout description and JScript or VBScript are used for data processing and scripting capabilities. HTA have been used by Symantec for Antivirus GUIs and Hewlett Packard Scanning tools GUIs. Although it is not recommended for exhaustive processing, HTA in combination with

60

ActiveX modules developed on lower level languages such as C++ or C# is a very powerful tool.

In this project in particular the flexibility of HTA allows easy development for third party modules, layout customization or application upgrades.

4.3.1.3 C++

C++ is the object oriented approach for C. Although its syntax complexity for classes manipulation is target of significant criticism, its overall performance, support for assembly and C coding and support for classes, turns it into a good choice for this project. The Microchip driver is also written in C++ making the development of the data handling code easier. C++ also supports ActiveX interfaces which are necessary for data exchange with the HTA GUI.

4.3.2 Operating System

There multiple light operating systems that can be used for embedded applications ranging from Embedded Linux to Microsoft Windows CE. However, with the release of MS Windows CE 6.0 [16] a platform builder was made available allowing for greater customization of the kernel thus making the operating system more flexible and application-oriented. Recent cellular phones, Personal Digital Assistants, automotive built-in computers or even systems for motion-sensitive door controllers such as those used on malls and other commercial areas have been running on distributions of Windows CE 6.0. The most popular distributions at the moment are Windows Mobile and Windows Automotive.

Windows CE 6.0 kernel may run under 1 megabyte of memory and can be programmed into a ROM preventing any disk storage. Also Windows CE is a real-time operating system with deterministic interrupt latency supporting up to 256 priority levels for interruptions. CE 6.0 raised most of the limitations from CE 5.0 such as the 32 process limit (now 32768) or 32 megabyte virtual memory limit which now is up to 2GB per process.

Windows Mobile is credited as one of the reasons for the PDA market increase in 40% in the first quarter of 2007. With the support for the .NET framework the number of applications for Windows CE is rising exponentially and it is foreseen that it will be the most popular OS for embedded systems in a near future.

It was based on this fact that the decision to use a Microsoft platform was made. As development for Windows CE required more man-weeks than were previously assigned to software development, the OS used was Microsoft Windows XP SP2 for 2 reasons:

• The migration from Windows XP to Windows CE is not difficult.

• In the worst case the software could run on a light distribution of Windows XP called Windows XP Embedded which provided the best of both worlds.

61

Windows XP Embedded is a customizable version of Windows XP SP2 on which drivers and unnecessary functionality may be removed in order to minimize the kernel load. The only restraint of Windows XP Embedded resides on the fact that it can only run on X86 architecture processors such as Intel’s Pentium4 while CE may run on a multitude of processors such as ARM, MIPS and Hitachi SuperH.

4.3.3 USB interface – C++ and ActiveX

The communication between the MCU and the On-board computer is done through an USB port. In order to allow different modules to communicate with the system, it was chosen to create an ActiveX interface for data transmission. In ActiveX communication, the application using the ActiveX object is referred as client and the ActiveX object is referred as ActiveX server or just server.

An ActiveX interface is registered in the system registry with a ‘unique’ GUID – Globally Unique Identifier. The GUID is a random sequence of 122 bits and while it does not guarantee to be unique, the probability to have two equal GUIDs in a single machine is very small. Since the object is reusable, there is no need for new compilation unless changes to the protocol are required. However, if any change is made to the server code, a new GUID should be used to identify the new object. Each release of an ActiveX object should have its own identifier.

The ActiveX designed supports two modes of operation, single thread or dual thread. On single thread mode the on-board computer behaves as a master and only listens to USB incoming communication if a previous request had been already done. Also, if a timeout timer expires no response is considered and a new request has to be done. In dual thread mode the ActiveX is constantly listening to incoming communication and allows the reception of sporadic data frames from other nodes. A second thread is also created just to take care of the transmissions made to the MCU. In order to protect the bus from concurrent communication the USB read and write routines are protected by semaphores that prevent further communication in case a transmission or reception is already being made.

The interface exposes several functions to the ActiveX client:

• read(variant* data) – function that returns the last 64 characters received from the USB port

• write(variant data) – function sends through the USB port the new 64 characters of data

• get_USBIF(double * pVal) – function that returns 1 if a new message arrived and is ready to be read with the read function. Returns 0 otherwise. IF stands for Interruption Flag.

• get_OF(double * pVal) – function that returns the number of missed messages. In case of a message being received while the previous had not been read yet, the Overflow Flag (OF) is incremented by 1.

• get_SYSIF(double *pVal) – function that returns 1 if there are system messages to be read,

62

for instance errors and warnings. Returns 0 otherwise.

This ActiveX interface does not implement events for real-time notification of received messages. Therefore the ActiveX client is responsible for polling the interruption flags and calling the read function in case something arrived.

The data transaction with the client is done with a BSTR – binary string – which should be able to carry all type of characters including the string terminator ‘\0’ as a valid value. Binary strings are supposed to carry its length on their header but for compatibility issues it was decided to represent all data in ASCII. Thus, the character with the hexadecimal code 0x5C would not be sent as the character 0x5C but as two characters, an ASCII “5” and an ASCII “C”. The transaction string had its length doubled since it requires two chars to represent a byte by its hexadecimal code in ASCII. This issue is supposed to be resolved in future upgrades to the server.

The simplified flowchart of the ActiveX server is presented in Figure 29. The mode depicted is the dual thread mode and the semaphores are:

• ACTIVECOM – Releasing this semaphore allows for other threads to use the USB port, waiting for it assures that the USB port is dedicated to that thread alone until released.

• NEWCOMMAND – Is released when a new command from the ActiveX client was issued, the thread responsible for sending information to the board will only attempt to use the USB port (wait for the ACTIVECOM semaphore) if the NEWCOMMAND semaphore was released.

• ACCESSHTABUF – similar to ACTIVECOM but for the use of the transaction buffer with the ActiveX client. In order to assure that the data sent to the ActiveX client is not corrupted, the ACCESSHTABUF should be caught and only released after all operations over the buffer have been done.

Send error message

No

Clear Inicialize Flags Open Connection USB connection Start Yes communication Load DLL with USB board Successful? buffer

Create two If threads were End Yes threads and three killed semaphores

No

Figure 29 – Flowchart of the main routine of the ActiveX C++ application.

63

4.3.4 HTML Application – Graphical User Interface

In order to create a user friendly interface with easy plug-in development, HTML was chosen as the language for the graphical user interface. Taking advantage HTAs – HTML applications – it was possible to create a fully trusted application with full access to file system and registry that allows for plug-ins written in HTML and Javascript or other scripting technologies.

The application consists of a core which will support communication with the USB driver, through the ActiveX object created before; an object to access file system and a structure representative of the vehicle itself, containing real-time data about the automobile status. It also includes a library for INI file parsing, a date object for calendar applications, clock functionality and timer objects for timeouts and intervals.

The application allows for a maximum of 10 plug-in scripts to be loaded. Each of the loaded scripts must have a basic common structure including three processes that are called upon module load event, module selection event and module deselect event.

A comprehensive tutorial on plug-in requirements and construction is added in Annex 4.

64

Chapter 5

Example Applications

5 Example Applications

65

5.1 Introduction

In order to test the application, three demonstration applications were designed. The first one uses the LIN bus and the others use CAN bus.

5.2 Applications

5.2.1 LIN – Suspension Control

5.2.1.1 Overview

LIN – Suspension Control is intended to control the strength of the four shock absorbers installed on the automobile. The strut system is a Kayaba AGX with 4 mode of operation. The modes are selectable by rotating a small circle on top of each shock absorber.

Figure 30 – Kayaba AGX sensitivity selector.

The desired mode of operation is selected by inserting a small screw-driver in the white straight line and rotate de inner black circle so that the small white dot is in the desired quadrant. In the figure above the white dot is selecting the mode 1.

The idea behind this first application is to read and write the new mode for each of the shock absorbers. The command will be sent via the USB interface to the Main Board, the Main Board will understand the command as a LIN command and pass it through the LIN interface. On the strut side, the LIN slave that subscribed the message identifier will process the desired value for each quadrant and output a control signal to each servo motor controlling the shock absorbers.

66

5.2.1.2 On-board Computer

The software for the On-board Computer will be a simple plug-in for the software. The plug-in consists of an HTML file for the layout of the application: CFGHTML.html and scripting file: CFGHTML.js.

Layout

Upon loading the SETUP.ini for the module, as in most of the other plug-ins, a new module icon will be placed on the top bar of the application as seen in Figure 31 (second icon on the module top bar).

Figure 31 – On-Board Computer Module.

The layout is divided into three areas:

• The Front and Rear Axis Link area where it is decided if the servos on the same axis will output the same positions or if the right and left servos on the same axis may have different positions at a given time.

• The Main area with sliding controls to select the mode for each the servos.

• The Setup area where the pulse duration for each mode is defined as well as the PWM base frequency.

Messaging

The hardware is supposed to be completely unaware of the desired mode since the same mode can be represented by different pulses if the servos were changed. Also, PWM base frequency may vary

67

and so it must be sent to the LIN bus.

The module makes use of two different messages: one to read the position of the servos and another to write the new positions. The messages’ format is described in Table 12.

The ordering message (to write the new positions) – ID=0xBA – will not have a handle associated since it does not expect a value to be returned. The requesting message (to read the current positions) – ID=0xFB – will have its response throughput to the defined handle function.

Table 12 – Suspension Module Messaging.

[10] [11] TYPE=MSG_ORDER_ID TYPE=MSG_REQ_ID BUS=BUS_LIN2_ID BUS=BUS_LIN2_ID PORT=1 PORT=1 VID=00000D0E VID=00000D0E PID=00000C0D PID=00000C0D INSTRUCTION=000000BA INSTRUCTION=000000FB LENGTH=0005 LENGTH=0004 DATA=ON_DEMAND DATA='' COUNT=0 COUNT=0 DELAY=0 DELAY=0 HANDLE=NONE HANDLE=_mod_SUSPENSION_GET

The ordering instruction will send 5 bytes. The four first represent the duration of the PWM pulses in tenths of millisecond for each servo and the last byte represent the PWM base frequency in Hz.

As for the requesting message, the response data field will carry four bytes, all containing the duration of the pulse that was last fed to each servo. This value is also expressed in tenths of millisecond.

5.2.1.3 Microcontroller and Servos

The hardware implementation was done with a microcontroller PIC18F4585, a LIN transceiver MCP201 and four Futaba S3003 servos.

Microcontroller

The user interface consists of three LEDs, one for transmission notification, another for reception notification and the other for transmission/reception error notification. The LEDs will be lit for approximately 13 ms every time that a message is successfully received or failed depending on the LED function. The schematic is depicted in Figure 32.

68

Figure 32 – Microcontroller Schematic.

The schematic represents only two outputs for servo control in order to minimize the picture size. The XTAL is a 20 MHz crystal coupled by two 15 pF capacitors and all resistors are 1 k Ω.

Servo Motors

The application hardware will rely on four servos to change the shock absorber mode. However, the specification of the wave form must be sent, in case servo motors other than the default were installed. The wave form used for position control on servo motors is a PWM wave usually with a 50Hz frequency and a duty cycle ranging from 2% up to 12%.

On this project the servos used for testing were the Futaba S3003. The servo characteristic is not totally linear as can be seen in the calibration results depicted in Figure 33.

69

S3003

90 80 70 60 50 40 30 20 10 0 -10 Rotation -20 -30 -40 -50 -60 -70 -80 -90

1 2 ,4 2 2 0,4 0,6 0,8 1, 1 1,6 1,8 2, PWM lenght

Figure 33 – S3003 Characteristic.

As the available servos (S3003) were only 180º servos, it was only possible to select three modes. As the main objective of the module is to be representative of full functionality, the angle range (180º) was still divided into 4 dummy modes regardless of the real modes:

• Mode 1: -90ºC – 0.4ms pulse

• Mode 2: -30ºC – 1ms pulse

• Mode 3: 30ºC – 1.6ms pulse

• Mode 4: 90ºC – 2.4ms pulse

Microcontroller Code

The microcontroller code is divided in LIN driver and Servo Control.

The LIN driver

70

Start

If Timeout = Enabled Yes Set Timeout Error AND TMR0IF = 1

No

If RCIF=1 No End

Yes

If OverRun=1 Yes Restart Receiver

No May be SynchBreak character: 13 Low bits create a framing error

If frame Clear Error Flag If Timeout = Start Timeout Yes If data=0 Yes Yes corrupted Set mode = SynchByte Enabled Timer

No No

No

mode = Add received data to Yes Add CRC byte ReceiveMode destination buffer

End

If last byte No

Yes

No Set CRC Start Idle State Timer If CRC error Yes error Flag Set mode = SynchBreak

No

Set Sucessful Transfer Flags

Figure 34 – Flowchart of the LIN driver for Slave Task - part 1.

71

No

If TXREG != Set Transmission If mode = Xmit Yes data Error Flag

No

Set Sucessful Start Idle State Timer If Data length = 0 Yes Transfer Flag Set mode = SynchBreak

No

If last byte Yes Send CRC End No

No

Send the next Add CRC byte data byte

Reset the SPBRG If mode = Yes If data != 0x55 Yes Set Transmission Error SynchByte Flag

No No Set mode = IdentifierMode Send frame ID

If mode = if ID parity = Set Parity Error Start Idle State Timer No End IdentifierMode OK Flag Set mode = SynchBreak

Yes Yes

Process ID and If mode = set new mode If mode = Xmit No No SynchBreak accordingly No Yes

Send first data byte Add CRC byte

If mode = If data = Enable Eusart Yes Yes Sleep Wakeup byte Configure SPBRG

No

Start Idle State Timer No Set mode = SynchBreak

End

Figure 35 – Flowchart of the LIN driver for Slave Task – part 2.

72

The LIN driver makes use of the Timer0 for Timeout condition and uses exclusively the EUSART for LIN communication. It is worth notice that the break character is detected by a corruption in the frame format since the break character is made of a minimum of 13 low bits, hence corrupting the framing structure.

The data bytes received are stored in an 8-byte global variable and the Frame ID is stored in a 1-byte global variable. These variables will be used on the servo control part of the code.

Servo Control

The core of the servo control code consists on a timer interruption. The timer used is Timer1 since Timer0 is in use for the LIN driver to generate the Timeout interrupt and Timer2 is used by the LED timeout routine in order to turn off the LEDs.

Timer1 is configured as 100 µs timer and each interruption generated by it will be referred as a “tick” from now on. Each block of ten ticks corresponds to 1 ms time interval. The interruption routine for each tick is represented on the flowchart presented in Figure 36.

The time table for each servo is stored in a 5-byte vector. The first four positions store the duration of the duty cycle for each servo in tenths of millisecond. The last position stores the duration of the entire PWM cycle in tenths of millisecond too.

Whenever a tick interruption is generated, the tick counter is incremented by 1 and the new value of the tick counter is compared with the PWM cycle duration, note that the ‘PWM cycle duration’ comprises both the ON interval and the OFF interval. If the number of ticks counted is equal or superior to the number of ticks supposed for the PWM cycle (thus exceeding the intended PWM period), all the servos’ outputs are set to HIGH to start a new wave form. Also, the total number of PWM cycles is incremented by 1 and compared to 150. If 150 PWM cycles have already passed, then the servos’ output are not set to HIGH and the TMR1ON flag is not initialized.

If the duration of ticks is not high enough to represent an end of cycle then the number of ticks counted is compared to the supposed number of ticks for each servo PWM control signal. If there is a match (representing the end of the ON interval for a given servo), that servo’s output is set to LOW and the next servo is compared.

At the end of the interruption service routine the timer is loaded with the respective value for the 1 ms interruption and is started again.

The main function of the application is an infinite loop that keeps checking the LIN driver for successful or failed transmission and clearing the watchdog timer.

The LIN driver outputs the result of the transmissions to a global variable. In case of transmission failure the LED3 is lit for 13 ms. In case of successful transmission the message identifier is

73

compared.

If it matches the reading command, the LIN driver has already dispatched the current PWM durations for each servo to the master task and so only LED2 is lit for 13 ms to notify success.

Figure 36 – Flowchart of Timer1 interrupt routine.

74

If it matches the writing command the new PWM durations are saved in the PWM vector. Also, they are written in the non-volatile EEPROM of the chip so that they can be restored after a Power-On Reset. The Timer1 is then set to initialize the 150 PWM cycles, in order to set the new position for all the servos.

Another important feature of the main function is that prior to start the infinite loop of the main process, it loads the previously stored values from the MCU EEPROM and start the PWM generation command signal. This feature is important because most low cost servos do not provide position reading. Therefore, the MCU enforces a value every time that it is reset. The default values that are only used until the first write command issued by the LIN bus are: PWM frequency of 50 MHz and 1.1 ms for each servo.

5.2.2 CAN – ECU RAM Reading

5.2.2.1 Overview

All internal combustion engines, with electronic fuel injection (EFI) require the use of a dedicated circuitry to determine the amount of time that an injector will stay open as well as the spark advance for more efficient combustion and fuel saving. This circuitry is often called Electronic Control Unit (ECU) in the automotive industry. In order to make better judgement about the period of time during which the injectors will stay open and the spark advance, the ECU also monitors important sensors such as the oxygen quantity on the exhaust and the engine temperature.

In the beginning of 1990, HONDA started monitoring approximately 30 sensors, ranging from critical functionality, such as the engine temperature, to optional devices. Examples of optional devices are the Knock sensor, Air Conditioned, or Electrical Load Detector (ELD).

It is of interest to be able to monitor these values and process the data as the automobile driver may wish. For instance, when the engine has not the right air fuel ratio, the O2 sensor may output a signal of rich or lean air fuel mixture. It is important for the driver to be able to realise this in order to be able to fix the problem. Also, the only temperature warning in an automobile is a simple analogue pointer that keeps rising in case of overheating. Most temperature damages are due to lack of perceptive warning about the internal temperature of the engine. If there was a way to monitor this sensor and act accordingly over its output, most damages would probably be avoided.

While some of this data is already throughput to the OBD2 interface in recent automobiles, the vehicle that was subject of this thesis only has a proprietary OBD1 protocol whose connector and communication standards are not known. The following sections describe the procedures made in order to be able to retrieve this information from the vehicle by reverse-engineering of the ECU.

75

5.2.2.2 On-board Computer Software

The datalogger module is configured as the first button on the module bar. In consists on a scripting file: _mod_datalogger.js and a layout file: CFGHTML.html.

LAYOUT

The module is a panel of information with real time data about the engine state and vehicle conditions that can be obtained from the ECU. Figure 37 depicts the module interface and the sensors that are monitored.

Most sensors’ values are surrounded by a rectangular box which colour and opacity will represent an interpretation of the value. For instance a colder than supposed temperature will be displayed in a blue box, while a hotter than supposed temperature will be displayed in a red box.

Figure 37 – Layout of the user interface of the Datalogger Module.

The sensors associated to the respective initials are given in Table 13.

Table 13 – Map of sensor displays.

INJ Injector opening duration MAP Manifold Air Pressure ADV Spark Ad vance Battery Voltage Battery Voltage VTEC VTEC ON or OFF Throttle Position Throttle Position STOICH Air/Fuel Mixture FAN Fan switch SPEED Vehicle Speed Sensor IAB Idle Air Bypass

76

RPM Rotation per Minute MIL Malfunction Instruction Gear Gear PWR STR Power Steering ECT Engine Coolant VTP VTEC Oil Pressure IAT Intake Air Temperature PCS Purge Control Solenoid

The module queries the ECU for updated values every 200 milliseconds meaning that variations up to 5 times per second are detected and displayed to the driver. These are particular important for RPM, Throttle, INJ and ADV fields. Even after selecting another module, the queries continue at a rate of a one query every five seconds.

The new values are captured via the three collective commands. The commands are explained in detail on next section.

MESSAGING

The module makes use of three similar messages:

Table 14 – Datalogger Module Messaging.

TYPE=MSG_REQ_ID TYPE=MSG_REQ_ID TYPE=MSG_REQ_ID BUS=BUS_CAN2A_ID BUS=BUS_CAN2A_ID BUS=BUS_CAN2A_ID PORT=1 PORT=1 PORT=1 VID=000055AA VID=000055AA VID=000055AA PID=000000CC PID=000000CC PID=000000CC INSTRUCTION=000000F0 INSTRUCTION=000000F7 INSTRUCTION=000000FE LENGTH=0008 LENGTH=0008 LENGTH=00008 DATA='' DATA='' DATA='' COUNT=0 COUNT=0 COUNT=0 DELAY=000 DELAY=000 DELAY=000 HANDLE=_mod_Datalogger_process HANDLE=_mod_Datalogger_process HANDLE=_mod_Datalogger_process

All the messages have the second lowest significant nibble 0xF and the least significant nibble the offset of the first sensor that they request. This way the response to 0xF0 will be sensor 0x0-0x6, since the first data byte is used for message Identifier validation. The response to 0xF7 will be sensors 0x7-0xD and the response to the last message will be sensors 0xE up to 0x14. The values addressed by 0x15 to 0x18 are not sensor values. They represent the 4 bytes of the CEL code and there is no interest on checking them in this application. This way, the first data byte of each frame may be used for ID confirmation to assure that the values are not misinterpreted as other sensors’ data.

It is important to note that these messages will be transmitted by CAN 2.0A and so the message identifier has 11 bits. Thus, the greatest identifier possible is 0x7FF.

77

5.2.2.3 ECU and CAN microcontroller

The vehicle subject to this project is a HONDA Civic Del Sol (EG2). The engine that is mounted on this chassis is a B16A2 which is a four cylinder, 1595 cm 3, naturally aspirated, 160 Horse Power engine. This model was designed in 1990 and HONDA ordered the ECU module to be designed by Keihin Indiana Precision Technology. The ECU is mainly composed by 3 areas:

• Sensor Input / Actuator Output

• Signal Conditioning

• Signal Processing

The Sensor Input and Signal Conditioning are out of the scope of this thesis. This application will focus on the Signal Processing and how to redirect it to the desired interface. A photograph of the three areas is presented on Annex 5.

SOFTWARE - INTERNAL ROM CODE

The Signal Processing in these ECUs is done by an OKI MCU – 66207. While it is possible to track all sensors signals from the Sensor connectors back to the sensor itself and analyse the signal conditioning by careful examination of the conditioning circuitry, it is not possible to read the code of a code protected MCU and determine the algorithm that is used by the MCU to process the data. This was supposed to make the task of reading the sensors via the MCU impossible. However, a design flaw was found on the OKI microcontrollers allowing the retrieval of program memory.

OKI MCUs can use both an internal or external ROM for program memory storage. The selection of the memory to be used is done by setting the digital input EA (pin 27) to either 0 V or 5 V. Since the MCU do not latch the value of the EA pin on reset, it is possible to redirect the data from the original ROM to the serial port and read it with a computer by flipping the state of EA and load a special routine from an external EPROM. Several software applications have been developed in order to read the code from the MCU and the binary files are available to download in the Internet, on pgmfi.org site.

The code has been mapped out by several individuals and the locations in the RAM where the various sensors values are stored are listed in Table 15. This listing includes the sensors that are available in the vehicle in use.

Table 15 – RAM Addresses of Sensor Data.

Sensor Value Data Byte RAM location (hex) Sensor Value Data Byte RAM location (hex) RPM LSB 00AC Intake Air Temperature 03C0

78

RPM MSB 00AD Vehicle Speed Sensor 00B4 LC Fuel – ROW (TABLE) 01D8 Engine Coolant Temperature 03C8 HC Fuel – ROW (TABLE) 01D9 Battery Voltage 00C3 Manifold Absolute Pressure 00A3 O2 00C2 Throttle Position Sensor 00B9 VTEC 0022 Fuel Column (TABLE) 01D2 CEL W1 B1 0112 Duration Injector LSB 01C6 CEL W1 B2 0113 Duration Injector MSB 01C7 CEL W2 B1 0114 Spark Advance 0305 CEL W2 B2 0115

SOFTWARE - EXTERNAL ROM CODE

In order to make the MCU run from an external ROM it is necessary to program with the original code a ROM of 32 kB (equal to the internal ROM of the OKI 66207). The ROM used was the EEPROM 27C256 with a time response below 170 ns. This time constraint was defined based on observation of the factory-chipped ECUs that already have code running from external ROMs (for fine tuning purposes).

The code changes consisted only on:

• Serial Port Reception ISR

• Checksum validation

The code inside the OKI MCU validates the checksum of the program memory and in case of defective coding the ECU enters a limp-home mode where very poorly chosen, yet safe, spark advance and injector pulse values are set. This mode is notified by a CEL/MIL on the dashboard.

In order to bypass this verification, the code is altered with an unconditional jump to the end of the checksum verification.

The Serial Port Reception ISR is more complex. The flowchart in Figure 38 and Figure 39 was implemented in assembly for OKI 66k series MCUs and programmed into the external ROM. The basic idea is to output through the serial port the value of specific RAM positions based on the command sent. For this purpose a vector with the RAM addresses will be created and the command received will be used as offset inside that vector.

79

Figure 38 – Datalogger Flowchart for 1-byte commands.

80

Store second byte from teh 3-byte command on the register r1

r1 = SRBUF If r3 == 1 Yes r3++

On third byte verify if the instruction is a read and if it No is to read from ROM or RAM

r0 = SRBUF If r3 == 2 Yes &DP = er0

Acc = *DP If r2 == 0x01 Yes @ RAM

No

Acc = *DP If r2 == 0x03 Yes @ ROM

No

Er1 = 0 r3++ Er2 = 0 DP = 0 Commands with length greater than 4 bytes are discarted

If r3 == 3 No Acc = 0x55

Send Acc

Yes 4-byte commands are supposed to write the RAM on the address speficied by the first 3 bytes If r2 == 2 No

Enable Interrupts Yes Return from ISR

*DP = SRBUF Acc = *DP

Figure 39 – Advanced Commands flowchart (continuation).

81

On the flowchart above DP is the Data pointer and is used to for instructions that retrieve data from the RAM. Acc is the processor Accumulator register and SRBUF is the Serial Port Receive Buffer. The registers r0-r5 are 8-bits registers for user applications. They may be referenced as 16-bits registers via the corresponding extended register:

Figure 40 – User Registers Table for OKI 66K MCU.

The code also supports 3-byte and 4-byte commands which are used for advanced functionality such as the reading or writing to a specific RAM address that is not listed in the sensor address vector: vec.

With the 3 and 4-byte commands code it is possible to read and write single bytes from the RAM and hence acquire the value of more data other than the mapped by the vector vec.

In order to test this code an emulator was designed in C#. The ECU emulator allows the emulation of values of interest such as the vehicle speed, vehicle PRM, Engine Temperature or even the the logic value of each bit belonging the OKI 66207 MCU ports 0 and 1.

The code of the emulator, besides the graphical user interface, consists of a replica of the C code implemented in the external EEPROM. Also, a vector of 32 kB was implemented in order to verify the offset mechanism for the indirect addressing inside the vector of RAM addresses. The emulator allows the modification of all of the values in real-time so it is possible to verify the accuracy and speed of the complete system.

Since the ECU outputs the values to a TTL serial communication port, a similar port was used in the computer with bit rate set to 38400, no parity, 8 data bits and 1 stop bit. FIFO buffers were also disabled.

The graphical user interface is depicted in figure 41.

82

Figure 41 – ECU Emulator GUI

SOFTWARE - MICROCONTROLLER CODE

The MCU used to establish the communication with the ECU was the same use for the LIN slave node: PIC18F4585.

The MCU port is configured to operate at 38400 bits per second and taking into account that a single byte transmitted via RS232 includes a start and stop bit, in this case of length 1, then the minimum number of bits transferred during a 1-byte command are 10 from the request, plus 10 from the response. 20 bits at 38400 bits per second represent an ideal maximum of 1920 commands per second.

MaxBitRate 38400 = = 1920 (10) MinBitsPer Frame 20

Since there are 20 addresses to be queried + 4 optional addresses for optional sensors such as Knock, PA or ELD the maximum number of complete cycles of refreshed data are:

MaxCommand sPerSecond 1920 = = 80 (11) MinCommand sPerCycle 24

Ideally it would be possible to have the sensors values updated at 80 times per second. Since it is neither necessary to have that high sampling rate nor recommended to have the bus at full use, the

83

decided sampling rate was set to be 0.1 of the maximum possible.

The RS232 requests were initiated by a timer interruption, the timer used was TIMER0. Since it was supposed to make 8 (80*0.1) complete cycles of requests and each cycle is composed by 24 individual requests the number of milliseconds between interruptions is given by:

NumberofCy cles ⋅CommandPer Cycle = 8⋅ 24 = 192 ⇒ 1 (12) ⇒ SecondsPer Interrupti on = 2,5 ms 192

Since the reception is optional, meaning that the MCU may not even respond to some of the commands in case of erroneous ROM code, the reception is assisted by an ISR as well. The code for both ISRs is given below. RCIF is the Receive Interruption Flag and TMR0IF is the TIMER0 Interruption Flag.

In order to keep track of the missed requests, the ISR that assists transmission monitors one flag and one error counter. The flag – pending – is set to 1 every time that a request is made and is set to 0 whenever a reception occurs. If the transmitter attempts to transmit while the flag “pending” is set to 1 then it assumes that the previous request was not attended and increments the error counter.

The value of the error counter may be requested via CAN bus at anytime by another CAN node.

In order to keep track of the current sensor being queried, the ISR also makes use of a global variable SERIALOUT that stores the offset of the wanted sensor. This value is incremented by 1 every time that the ISR is called and is reset when reaches 0x18.

The 18F4585 user visual interface is made of 2 LEDs. A green LED for successful CAN transmission notification and a red LED for error notification on the CAN bus.

Both LED, upon lit, start a timer – TIMER2 – of 13 ms after which they are turned off.

Although the PIC18F4585 has a built-in driver for CAN bus, the standalone controller MCP2515 was still used in case of future firmware update. Interruption pins, the Buffer Full and the General Interrupt (configured only for error notification) are connected to the general purpose pin RB4, RB5 and RB6 since these pins have the “on-change” interrupt mode. When a CAN message successfully arrives or an error is detected, the MCU ISR queries the MCP2515 flags and checks for either errors or successful messages.

In case of error, the red LED is lit and the TIMER2 is started. Also all the CAN driver is reset. In case of successful reception, the MCP2515 is queried for the data length, the message Identifier and the data bytes and acts upon them accordingly.

84

Figure 42 – RS232 interface ISR Flowchart.

The message handling function discards all commands which have a length greater than 1-byte

85

meaning that only the single sensor query message explained above is implemented (no 3 and 4 byte commands are implemented). Also, in order to reduce the load on the CAN bus, three special commands were implemented. Since most values are 1 byte long and a CAN frame can carry a maximum of 8 data bytes, collective frames were defined. This way, by querying the CAN node only 3 times it is possible to get an updated value of the 24 sensors such as explained in the section above.

Start

If RBIF==1

RBIF = 0 IF_byte = CANFlags

Set REDLED If IF_byte == Yes Set TIMER2 Exit ERROR Clear CANFlags

No

IF Message Set GREENLED Yes Received Set TIMER2

If Buffer1 == Yes Read Buffer1 FULL

No

Read Buffer0

Exit Handle Request

Figure 43 – CAN Interface ISR Flowchart.

An important note is that the sensor value is transmitted in raw format, there is no unit conversion or data interpretation since the sensors may be updated for different ones. For instance, the stock O2 sensor may be upgraded to a wideband sensor. It is up to the application layer on the On-board

86

computer to interpret the value received.

HARDWARE – ECU

In order to force the MCU to execute program memory from an external ROM and to enable the Serial Port Connector minor hardware changes must be done inside the ECU.

The ECU for this specific vehicle has the model designator P30. Since some models require factory modifications either because they are connected to more sensors such as Knock detector or Atmospheric Pressure sensor or because they must be tuned for different types of fuel as it happens in Japan, the ECUs are already prepared to run external EPROMS [17].

Figure 44 contains an enlarged photograph of the area reserved for the external ROM.

Figure 44 – Photograph of the P30 MCU.

The red outlined area above depicts the space that requires soldering of new components. The new components required are:

• One EPROM 27256 (32 kB)

• One 8-ports, tri-state D-Type Latch (74HC373)

• Two 0.1 µF ceramic capacitors

• One 1.1 k Ω Resistor

• One shunt for EA pin

87

The shunt is used to set EA pin to the ground and so is used on J1 which connects EA to pin 32 (GND).

The 1.1 k Ω resistor is to connect the ground to EPROM pin 20. Pin 20 is the Chip Enable of the EPROM and must be grounded to enable the ROM.

Both capacitors are for bias purposes. One of the capacitors (C52) is used for voltage transient filtering on EPROM’s VCC and C52 is used for the tri-state latches.

The blue outlined area represents the Serial Port Connector. In order to connect it to an RS232 D-9 connector the pinout is described in Figure 45.

Figure 45 – Schematic of the P30 ECU custom components.

Where CN2 pins are given in Table 16.

Table 16 – CN2 Connector Pinout.

Pin Number Description 1 Ground 2 RX – Receives the data from the Can board 3 +5 Volt 4 Tx – Sends the data from the ECU to the CAN board (vi a RS232) 5 Not Used

The board designed had to be able to communicate with this connector – CN2 – and with the CAN interface so that the data could be sent to the On-Board Computer. Pins 2 and 4 of the CN2 connectors are connected to PORT3 pins 3 and 2 of the OKI MCU.

Although the transmission request pins are not used by the current firmware on the PIC, the pins were connected to PORTA pins on the MCU for future use. Also, Clockout pin was hooked to a single pin exterior connector for debug purposes.

88

The schematic of the device is presented in Figure 46.

Figure 46 – ECU to CAN interface.

The connector used for the CAN bus interface was a RJ10 as well as in the Main Board.

5.2.3 CAN – Thermometers

5.2.3.1 Overview

In order to give the ability to read the temperature inside the vehicle and compare it with the temperature outside the vehicle a board was designed. This board does not require an additional module since it is supposed to be included in all the distributions of the complete system. The

89

messaging entries are also included in the message offset reserved for system communication.

5.2.3.2 On-Board Computer

The temperatures will be depicted in a dedicated area reserved for the effect as can be seen in Figure 47.

Figure 47 – Temperature interface on the GUI.

The first temperature represents the temperature inside the vehicle while the second represents the temperature outside the vehicle.

The module communicates via CAN bus and refreshes the temperature information every 5 seconds.

MESSAGING

The message specification for this application is the following:

TYPE=50 BUS=104 PORT=1 VID=00000000 PID=00000000 INSTRUCTION=00000100 LENGTH=0009 DATA='' COUNT=-1 DELAY=5000 AUTORUN=true TIMEOFFSET=1000 HANDLE=_util_TEMP_meter

A length of 9 in a CAN bus system is interpreted by the application as a request of a remote frame. This type of frame instructs another node to actually publish the correspondent data frame with the values of the thermometers.

5.2.3.3 Microcontroller and thermometers

On this application the MCU used was PIC18F4585 again. This time the interface was created using the native ECAN module of the PIC and not using the MCP2515 stand-alone controller. This was due to the need of this module to be the smaller possible. The module was designed to be completely implemented with surface mount devices to reduce size.

90

The thermometers used were digital thermometers so that the electromagnetic noise would not corrupt the value of the temperature analogue transmission. The chosen thermometers were DALAS DS18S20 [18] and these are 9 bit digital thermometers which require a custom driver for communication.

The thermometers support multiplexing with other devices of the same types, on the same bus, require a 1-wire data bus and support parasite power (getting power from the data line in IDLE state).

The thermometers require a maximum temperature conversion time of 750 ms counting from the CONVERT TEMPERATURE command. This interval should be respected especially in parasite-powered mode.

SOFTWARE

Since the protocol to communicate with the thermometers was developed by DALAS a device driver was implemented in C to run in the Microcontroller. The driver constantly monitors the value of the BUS and communicates with each thermometer in Master/Slave architecture. The timing precision may go as high as 10 µs and as low as 480 µs. For lower frequency communication where the expected periods would be around 480 µs a timer was used to generate the interrupts – Timer3. For temperature conversion time event Timer0 was used with a 1 second interval.

The flowchart bellow illustrates the behaviour of the designed driver.

The master (MCU) may assume 6 different states:

• IDLE – No communication being made.

• RESET – Sets the bus to low for 480 µs in order to enforce a response from slaves.

• PRESENCE – Listen for bus activity and activates flag NODES_EXIST if nodes respond.

• ROM_COMMAND – Sends a ROM command: SKIP_ROM, READ_ROM, MATCH_ROM.

• FUNC_COMMAND – Transmits the command for the desired function.

• DATA – Reads or Write the data necessary after a ROM_COMMAND state or FUNC_COMMAND state.

The driver also makes use of several global variables:

• BUS_LATCHED – Latches the bus during ISR to avoid changes during context reposition.

• DATA_BUFFER[9] – a 9-byte vector used for communication with the slaves.

• COMMAND – variable that stores the command code to be sent.

91

• FUNCTION – variable that stores the command code to be sent when COMMAND has a ROM command code.

• SUCCESSFUL_TRANSFER – True if transfer was successful.

• ERROR_ON_TRANSFER – True if transfer failed.

Start

Set Timer1 MASTER_STATE == Finished COMMAND == Yes Yes Yes COMMAND = MATCH_ROM FUNC_COMMAND transmission CONVERT_T FUNCTION = READ_SCRATCHPAD

No No Clear buffer COMMAND == Bit_limit = 72 Yes READ_SCRATCHPAD MASTER_STATE = DATA DS1820_data() DS1820_command()

No

Clear buffer COMMAND == Bit_limit = 1 Yes READ_POWER_SUPPLY MASTER_STATE = DATA No DS1820_data() No

Set Error

Exit

MASTER_STATE = FUNC_COMMAND MASTER_STATE == Bits counted COMMAND == Yes Clear Ints Yes Yes COMMAND = FUNCTION DATA == Bit_limit MATCH_ROM DS1820_command()

No No

Set CRC == OK Yes DS1820_data() Success

No No

Set Error Exit

Figure 48 – Flowchart of the DS18S20 driver (Part 1).

92

No

MASTER_STATE == Finished Yes Yes Turns Timer3 Off ROM_COMMAND transmission

COMMAND == Yes Clear buffer READ_ROM

No

Bit_limit == 64 COMMAND == Yes MASTER_STATE = DATA MATCH_ROM DS1820_data() No No

No MASTER_STATE = FUNC_COMMAND COMMAND == Yes COMMAND = FUNCTION SKIP_ROM DS1820_command()

No

Set Error Exit

DS1820_command()

MASTER_STATE == Yes Activity On Bus Yes BUS == 0 Yes NODES_EXIST = true PRESENCE

No

No Set Error

MASTER_STATE = NODES_EXIST TMR3IF Yes Disable ints Yes ROM_COMMAND == true No DS1820_command()

No

No Set Error Exit

TMR3 = 480us MASTER_STATE == Activate RX Yes RESET MASTER_STATE = PRESENCE RBINT_ON()

No

TMR3 = 480us Activate TX MASTER_STATE == IDLE Yes MASTER_STATE = RESET BUS = 0

No

Figure 49 – Flowchart of the DS18S20 driver (Part 2).

93

HARDWARE

The hardware was reduced to a minimum. On this board it was assumed that a steady power supply of 5 V was provided from the Main Board and so there is no buck converter to step-down the battery voltage to the MCU VCC levels.

The hardware included was a PIC18F4585 for DS18S20 and CAN bus driver software; a MCP2551 CAN bus transceiver; 3 status LEDs; 1 20 MHz crystal; 2 DS18S20 thermometers and the minimal required resistor and capacitors for MCLR and DS18S20 bus pull-up and XTAL configuration.

The schematic of the circuit is presented in Figure 50.

• T1 and T2 represent the 2-pin headers to connect to the parasite-powered Termometers.

• POWER represents the 5V DC power supply.

• DEBUG represents the 2-pin header to activate the debug LEDs.

• RESET represents the 2-pin header to reset the MCU.

• ICD2 represents the 2-pin header to connect PGD and PGC to the ICD2 programmer and debugger.

• CANBUS represents the 2-pin header to connect to CANH and CANL on the CAN bus.

Figure 50 – Thermometers schematic.

94

5.2.4 Media Player

5.2.4.1 Overview

In order to give the ability to play video and audio file to the driver a version of MS Windows Player was implemented as a module. The application is pure software so there is only a section dedicated to the on-board computer and none to the hardware implemented.

5.2.4.2 On-Board Computer

The application makes use of the Windows Media Player 11 SDK that is made available from Microsoft through an ActiveX Interface. This was it was possible to implement a full featured media player with simple HTML and Jscript.

The module captures the CdromMediaChange event which allows for automatic detection whenever a new CD or DVD is inserted. This function, associated to a slot-loading DVD reader, replaces completely the current hi-fi systems in the automotive industry. Also, all the functionality expected from a CD / DVD player is provided: Full Screen, interactive media progress bar, shuffle mode, playlist access and HDD navigation, play, stop, pause, FF, FR and force CD loading (in case the CD is already inserted and not playing) are accessible via the touch screen interface.

In order to keep the media playing while navigating through the other modules a special modification had to be done. The player canvas does not belong to the Document Object Model (DOM) of the module itself but to the DOM of the host application. This means that the media player belongs to the application (even if no mode was loaded) but this module in particular provides a GUI to display it and use it.

Figure 51 - Media Player GUI

95

Chapter 6

Conclusions and Improvements

6 Conclusions and Improvements

96

6.1 Conclusions

The aim of this thesis was to design, prototype and test a complete application for an on-board console that allowed the driver to access, observe and control potential devices, placed throughout a vehicle and connected through two serial buses. The objective was achieved and the following conclusions are intended to enhance future versions of this application or similar equipment.

• The first conclusion is that a PIC microcontroller should not be used to implement more than two buses’ interfaces. The microcontroller has a maximum of three serial ports and usually one is used to report back to the vehicle driver, either through a node on the bus or a directly connected computer via USB / RS232. Also, PIC microcontrollers support a maximum bit rate of 12 Mbps for USB, far inferior to the 480 Mbps specified in the standard.

• Another conclusion is that LIN nodes should be used whenever possible for the lowest possible node cost. Not only they do not require an external oscillator for precise Time Quanta generation like CAN (for 1 Mbps transfer), but they also do not need power supply circuitry since the transceiver provides a 5 V, 20 mA power output. This allows the reduction of the entire component list to a single MCU and transceiver for fully functional LIN 2.0 node.

• Regarding CAN, microcontrollers with a built-in CAN driver should be considered for mass production. The available standalone CAN controllers such as the one used MCP2515 require a dedicated crystal and do not have a build-in transceiver thus increasing the total cost of the node, power dissipation and consumption.

• Regarding the communication with the ECU, this approach for the Honda specific OBD1 connector is fast enough for the most demanding applications, reaching a theoretical maximum of 1920 sensor queries per second. This mechanism is fast enough for real time tuning of the injection and ignition advance tables. However, in order to maximize the precision of the table entries, the addition of four new sensors would be required: EGT – exhaust gas temperature for control of the explosion quality and temperature, Knock sensor to detect explosions that occur before the specified time, a wideband O2 sensor for more accurate measurement of the quantity of Oxygen on the exhaust and a atmospheric pressure sensor for correct calculation of intake’s air quantity.

97

6.2 Future Enhancements

As for future improvements, the suggestions will be made for each area of design: On-board Computer and Main Board.

• The On-board computer should have very low power consumption and a very short recovery time from suspension mode. A future approach to this type of interface should be implemented with a low power processor, probably an ARM running an operating system such as Windows CE 6.0.

• The software running on the On-board Computer should be designed to meet the new timing requirements of the new protocols. For instance for MOST, which has a large bandwidth reaching up to 25 Mbps, the software should be able to handle each of the streaming data packets. A suggestion for the new language used is C# which is fully supported by Windows CE 6.0 and allows the creating of fast ActiveX components.

• For the Main Board, an interface for two more buses should be added: FlexRay for critical application and MOST for multimedia data streaming. In order to become fully compatible with the actual products on the market, an interface for K-line (ISO 9141) for low speed peripheral communication should also be implemented.

• Concerning the implemented protocols, minor changes on the software should be made in order to correctly handle all versions of CAN and LIN, especially LIN 2.1 which was released while the thesis was being developed. Some improvements on LIN node configuration should also be implemented such as message ID assignment via NAD addressing.

• The last suggestion would be the implementation, within the ECU CAN node, of a NVRAM for real-time programming of ECU MCU code. Since the EA pin of the OKI 66207 is not latched at startup it is possible to keep loading new maps in real time and change the injectors and ignition in real time for optimum engine tuning.

98

Annex 1

LIN Framing Structure

LIN Framing Structure Generators

99

LIN Framing Structure

The frame structure is described in Figure 52.The Frame Slot is the time slot reserved for a complete frame including Header, Response and Interframe Space.

Most of the symbols in LIN protocol are comprised into bytes and use the standard byte field which is made of 1 start bit, 8 data bits and 1 stop bit.

Figure 52 – Representation of the Byte Field in LIN.

The Header is made up of a break symbol which takes at least 13 bit time on Low logic value including start bit. The break is limited by a break delimiter that is at least one nominal bit time long at High logic value. Slaves should be able to consider any signal with at least 11 nominal bit times at Low level a break signal.

Figure 53 – Representation of the Frame Slot in LIN.

After the break symbol a Synch byte is sent. The Synch byte is a byte field with the value 0x55 and as any byte field, it has a start and stop bit. The value 0x55 is used to maximize transitions between logic values in order to let slaves synchronize with the master. It is clear the endianness of the LIN protocol in this Synch field where the LSB is the first to be transmitted.

Figure 54 – The Synch Byte in LIN.

100

Right after the Synch byte an ID byte is sent to route the message. The ID byte is called Protected Identifier because only 6 bits are dedicated to the ID and the other 2 are used for identifier parity. With only 6 bits for the message identification, the ID ranges from 0 to 63 and is organized in the following way:

• IDs from 0 to 59 (0x3B) are used for signal-carrying frames. • ID 60 (0x3C) and 61 (0x3D) are used to carry diagnostic data • ID 62 (0x3E) is reserved for user-defined extensions • ID 63 (0x3F) is reserved for future protocol enhancements

The parity bits are calculated as shown in the following equations:

P0 = ID 0 ⊕ ID 1⊕ ID 2 ⊕ ID 4 (13)

P1 = ¬(ID 1⊕ ID 3⊕ ID 4 ⊕ ID )5 (14)

Figure 55 – The Identifier Field in LIN.

A frame carries between 1 and 8 bytes of data. The number of bytes within a frame with a known identifier must be agreed by the publisher and all subscribers. Each data byte is transmitted in a byte field.

Figure 56 – The Data Field in LIN.

The last field of the frame is the Checksum. The Checksum contains the inverted eight bit sum with carry over all data bytes up to LIN version 1.3 and over all data bytes plus the Protected Identifier in LIN version 2.0. The checksum model used up to version 1.3 is called Classic Checksum. The checksum model used in LIN version 2.0 is called Enhanced Checksum.

Taking a minimum length of 13 bits for the Break Symbol, a 1 nominal bit time for the Break Delimiter, 10 bits for each of the byte fields of both the Synch Field and Protected Identifier we have a minimum nominal 34 bit times for the Header.

101

TH _ N =34 *Tbit (15)

The response nominal length is dependent of the number of data bits to be transmitted. The formula is given by equation 16:

TR _ N = 10 ⋅ (Nbytes + Cs *) Tbit (16)

Where “10” represents the 10 bits of the standard byte field, Nbytes represents the number of data bytes to be transmitted and Cs the checksum byte.

The nominal frame time is given by the sum of both times:

TF _ N =TH _ N + TR _ N (17)

The time slot allocation for each frame slot is based on the nominal duration of an ideal frame plus 40% of tolerance:

TFS _ N = 4.1 ⋅TF _ N (18)

102

Annex 2

A2 - Schematics

A2 - Schematics Generators

103

Figure 57 – Schematic of the Main Board.

104

Figure 58 – Schematic of the ECU Datalogger

105

Figure 59 – Schematic of the Thermometer Board

106

Figure 60 – Schematic of the Suspension Board

107 Annex 3

MCP2515 Register Description

MCP2515 Register Description Generators

108

Within the Main Board microcontroller code there is an initialization routine of the MCP2515 that configures several registers of interest. Although code is supplied and the calculations of the necessary Time Quanta for each segment explained, there is no description of the registers.

In this annex the most important configuration registers of the MCP2515 will be explained so that the limitations of the hardware may be better comprehended.

REGISTER: CNF1 – 8-bit – Configuration 1 (Address: 0x2A)

Bit 7-6: SJW<1:0>: Synchronization Jump Width Length – Used to define the length of the SJW

Bit 5-0: BRP<5:0>: Baud Rate Prescaler – Use to set the baud rate of the BUS based on the Fosc

REGISTER: CNF2 – 8-bit – Configuration 2 (Address: 0x29)

Bit 7: BTLMODE: Phase Segment 2 Bit Time Length – Use to specify the way how the length of the Phase Segment 2 will be determined.

Bit 6: SAM: Sample Point Configuration – Used to enable or disable multisampling of each bit.

Bit 5-3: PHSEG1<2:0>: Phase Segment 1 Length – Length in Time Quanta of Phase Segment 1

Bit 2-0: PRSEG<2:0>: Propagation Segment Length – Length in Time Quanta of Propagation Segment

REGISTER: CNF3 – 8-bit – Configuration 3 (Address 0x28)

Bit 7: SOF: Start-of-Frame Signal – Select function of CLKOUT pin

Bit 6: WAKFIL: Wake-Up Filter – Enable or disable wake-up filter

Bit 5-3: UNIMPLEMENTED

Bit 2-0: PHSEG2<2:0>: Phase Segment 2 Length – Depending on BTLMODE bit may determine the length in Time Quanta of the Phase Segment 2.

109

REGISTER: CANCTRL – 8-bit – CAN Control Register (Address: 0xXF)

Bit 7-5: REQOP<2:0>: Request Operation Mode – Set MCP2515 to several operating modes such as configuration or normal modes.

Bit 4: ABAT: Abort all Pending Transmissions – Request to terminate all pending transmissions.

Bit 3: OSM: One-shot Mode – Enables of disables the mode where controller will retry each failed attempt to transmit.

Bit 2: CLKEN: CLKOUT Pin Enable: Enables or Disables CLKOUT Pin

Bit 1-0: CLKPRE<1:0>: CLKOUT Pin Prescaler: Prescaler for CLKOUT if function is set to clock output (SOF bit).

REGISTER: CANINTIE – 8-Bit – Interrupt Enable for INT pin (Address: 0x2B)

Bit 7: MERRE: Message Error Interrupt Enable

Bit 6: WAKIE: Wakeup Interrupt Enable

Bit 5: ERRIE: Error Interrupt Enable

Bit 4: TX2IE: Transmit Buffer 2 Empty Interrupt Enable

Bit 3: TX1IE: Transmit Buffer 1 Empty Interrupt Enable

Bit 2: TX0IE: Transmit Buffer 0 Empty Interrupt Enable

Bit 1: RX1E: Receive Buffer 1 Empty Interrupt Enable

Bit 0: RX0IE: Receive Buffer 0 Empty Interrupt Enable

110

Annex 4

Plug-In Tutorial

Plug-In Tutorial Generators

111

This annex will explain the requirements to create new plug-ins for the On-Board Computer software. Each plug-in must be comprised within a simple directory and its name must start with “_mod_”. Inside the folder there must be at least 3 mandatory files:

• setup.ini – a file describing the module.

• An HTML file – describing the layout of the module to be shown when activated.

• A Jscript file – defining the various processes of the module, including the two mandatory

The name of all processes and variables declared by a plug-in must start with its name. For instance, for a module that would take care of the suspension system of the vehicle, a possible name would be: “_mod_SUSPENSION”. All the processes and variables must have their name started with “_mod_SUSPENSION_” to avoid conflicts with other modules variables and processes. A module may set up to 10 different messages to be sent onto the various buses. A module can send information or request information to any bus since all message configurations are independent from each other. Also a module may not send any message and work only with the existing data.

The graphical interface of the module is defined by the CFGHTML file specified on the setup.ini file. The HTML will be rendered on a canvas with 800 pixels of width and 600 pixels of height. The CFGHTML must have any form of text, even if invisible HTML such as “

”.

The scripting file JSCRIPT must have the prototypes of, at least, these three functions since they will be called if the module is ACTIVE: function _mod_NAME_UnLoad () { } //called when another module is activated function _mod_NAME_ onLoad () { } //called when the module is activated (clicked) function _mod_NAME_ startup () { } //called when the application starts, always called if the module ACTIVE flag is set to true.

A4.1 - Setup.ini description

The setup.ini file defines several aspects of the module and its structure should be the following. The text in caps is supposed to be user defined. Values limited by brackets represent the possible values to be used on that field, from which only one can be chosen.

[_mod_name] FOLDER=_mod_name MENU= {0,1,2,3,4,5,6,7} CFGHTML=HTML_FILE_NAME JSCRIPT=JSCRIPT_FILE_NAME VID=0x00000000 PID=0x00000000 PROTOCOL=PROTOCOL_DEFINES

112

BITRATE=bitrate ACTIVE= {0,1}

_mod_name: Must start with _mod_, case sensitive and differente from any other module installed.

FOLDER: The name of the folder where the files will be stored. Must be equal to module name.

MENU: In case the module is supposed to appear on the top menu bar of the application it must have its menu property set to 0 or greater and lower than 8. It also must have two png icons named: icon_PRESS.png and icon_UP.png for menu representation.

CFGHTML: the name of an HTML file contained inside the folder to be used as layout when the module is activated (clicked).

JSCRIPT: the name of a Jscript file contained inside the folder to be used as scripting source when the module is loaded and activated.

VID: Vendor ID or the four MSB of PRODUCT ID (not used in current version)

PID: Product ID or the four LSB of PRODUCT ID (not used in current version)

PROTOCOL: Not used in the current version. Should take on of the following values if the module is dedicated to any bus node in particular:

BUS_SYS_ID BUS_USB_ID BUS_LIN11_ID BUS_LIN12_ID BUS_LIN13_ID BUS_LIN2_ID BUS_CAN1_ID BUS_CAN2A_ID BUS_CAN2B_ID BUS_MOST_ID BUS_FLEXRAY_ID BUS_OBD0_ID BUS_OBD1_ID BUS_OBD2_ID

BITRATE: Not used in the current version. Should be in Hertz.

Active: active status must be set to 1 or 0 in case the module is supposed to be running when the application start. For most applications active must be set to 1 all the times.

After the module description an entry for each message should be defined:

[message]

113

type={ANY OF THE TYPE IDENTIFIERS} bus={ANY OF THE BUS IDENTIFIERS} port=1 vid=VID_NUMBER pid=PID_NUMBER instruction=INSTRUCTION_ID length=LENGTH_IN_BYTES data=DEFAULT_DATA count=NUMBER_OF_TIMES delay=DELAY_IN_SECONDS AUTORUN=true TIMEOFFSET=1000 handle=PROCESS_TO_HANDLE_RESPONSE message: Message offset within the received. Must be a number between 0 and 9. type: One of the following values:

MSG_REQ_ID //A request than expects a response MSG_RESP_ID //Response to a previous request MSG_ORDER_ID //Ordering instruction that does not expect a response MSG_SPORADIC_ID //A sporadic communication from the node that was not triggered by a request bus: One of the values specified in the box above, under PROTOCOL key for the module description. vid: Vendor ID or the four MSB of PRODUCT ID in hexadecimal (should de 0x00000000 for CAN) pid: Product ID or the four LSB of PRODUCT ID in hexadecimal (should de 0x00000000 for CAN)

Instruction: the ID of the instruction in hexadecimal length: the length in bytes of the data bytes. Must be set to 9 to request a remote frame in CAN. data: the default data to be sent in case of an MSG_ORDER_ID or MSG_REQ_ID message. count: number of times that the message will repeat transmission after started. -1 for infinite. delay: Time interval in milliseconds between retransmissions.

AUTORUN: Boolean. Set to true if the message is intended to start transmission on startup.

TIMEOFFSET: Time interval in milliseconds to wait before start transmitting the message in case of AUTORUN set to true. handle: Name of the function that will handle the response from the node in case of a MSG_REQ_ID or MSG_SPORADIC_ID. Must be defined in the module scripting file.

_mod_SETUP

114

The application has one resident module called _mod_SETUP which is responsible for loading new modules. Once a module is created with the specified structure entering this module allows for some customization such as changing the position of the module in the menu bar or setting the active/inactive state of each one of them. The application will add the module to mods_config.INI and the respective messages to msg_desc.ini. Whenever a module wants to send a message to the buses it must address its messages by the respective index. For instance first message declared has index 0 and the second message has index 1. The message_offset is a property of the module assigned by the application when the module is first loaded.

A4.2 - API Reference

• Class: _module

For each new module loaded, the application creates a _module object which describes the loaded module.

Properties: name – returns the name of the module folder – returns the folder of the module menu – return the position of the module on the menu HTML – returns name of the HTML file for module layout JScript – returns the name of the script file for module scripting msg_offset – returns the offset of the first message in the global list of messages active – returns the state of the loaded module, if active or not

Methods: printf() – returns a string with all of the properties of the module

• Collection: modules

All the _modules are in a collection called modules. Each entry of the collection is a single _module . It is advised that each module stores in a variable a reference to its own _module object. This way one can access the module properties without having to browse the entire list of modules every time.

Properties: length – returns the number of _modules inside the collection

• Class: _message

Each _message object describes a respective message associated with a module.

Properties: type – returns the TYPE field of the message bus – returns the BUS field of the message

115

port – returns the PORT field of the message devIDmaj – returns the device-ID four most significant bytes devIDmin – returns the device-ID four least significant bytes instID – returns the instruction ID length – sets and returns the length of the DATA field count – sets and returns the number of times that the message is supposed to be sent, 0 for infinite delay – returns the delay between consecutive transmissions of the message handle – returns the function that will handle the response to the message data – sets and returns the DATA field in the message

Methods: print() – returns a string with all the properties of the message in raw format printf() – returns a string with all the properties of the message in HTML format

• Collection: messages

All messages are confined in a collection named messages .

Properties: length – returns the number of _modules inside the collection

• Object: EVTS

EVTS is the events table and all running event must be added to this list in order to have its transmission scheduled. The EVTS object has no properties and has six methods. The EVTS is a public object and its class is not supposed to be instantiated again.

Methods: add(message) – adds an event to the event table print() – returns a sting with all the pending messages stop() – stops and discards all pending timers for message transmission. start() – loads new timers for each pending message set() – browses the collection messages and adds an event for each press(message_ID, transmission_count) – starts a single event defined by message_ID.

Most module will only use the press() method since they only need to force the event table to schedule the transmission of their messages. Also adding an event to the event table does not mean that the message will be transmitted. To ensure transmission either press() or start() must be called.

A4.3 - API usage example

A basic module should have the three methods, one for when it is loaded by the system and another two for each time it is activated or deactivated. Assuming a module to control the vehicle’s suspension, its name would likely be _mod_SUSPENSION. The scripting file has to implement the following processes:

116

function _mod_SUSPENSION_onLoad() for each time it is activated and loaded into the canvas function _mod_SUSPENSION_UnLoad() for each time it is deactivated and unloaded from the canvas function _mod_SUSPENSION_startup() for the first time the module is loaded

And example of message transmission: function _mod_SUSPENSION_send(offset) { messages[_mod_SUSPENSION_module.msg_offset+offset].data = “1234” EVTS.press(_mod_SUSPENSION_module.msg_offset+offset,1); }

A good practice is to define a variable to store a handle to the module object so the following code should be added as well: var _mod_SUSPENSION_module = null; function _mod_SUSPENSION_startup() { for (var i=0; i

Special care must be taken regarding timers that display information on the canvas. If the module is unloaded the canvas HTML references will be lost and so, the timers must be cleared. For those cases the _mod_SUSPENSION_Unload function should be used.

117

Annex 5

P30 ECU Topology

P30 ECU Topology Generators

118

The ECU has 3 distinct areas which were referenced throughout the thesis. These are:

• Connectors

• Signal conditioning

• Signal processing

Although these areas are not explored in any detail other than the necessary for the development of the prototype, the pictures of the modules are presented in Figure 61.

Figure 61 – Detail photograph of the MCU and external EEPROM inside the ECU.

119

Figure 62 – Photograph of Complete Signal Processing area.

Figure 63 – Photograph of Complete Signal Conditioning Area.

120

Figure 64 – Photograph of ECU connector part A B and C.

Figure 65 – Identification of the pins of ECU connector A.

Figure 66 – Identification of the pins of ECU connector B and C.

121

Annex 6

A6 - MCUs Code

A6 - MCUs Code Generators

122

123

References

References

[1] Ming-Chun Chen, CommonWealth Magazine – In a Race for Precision? Start Your Engines! (URL) [web page], Mar 14 2007; [2] Various Authors, Wikipedia – FlexRay (URL) [web page], last edited Dec 14 2007; [last accessed Dec 14 2007] [3] Microsoft, Windows Automotive Overview (URL) [web page]; [last accessed Dec 10 2007] [4] Goepel, Automotive Test (URL) [web page]; [last accessed Dec 10 2007] [5] Leroy Davis, Automotives Buses (URL) [web page], last modified Nov 24 2007; [last accessed Dec 10 2007] [6] Robert Bosch GmbH, CAN Specification (version 2.0), 1991 [7] LIN Consortium, LIN Specification Package (revision 2.0), 2003 [8] Christopher A. Lupini (Delphi Delco Electronics Systems), Multiplex Bus Progression, Mar 2001, SAE Technical Paper Series [9] Microchip, PIC18F2455/2550/4455/4550 Data Sheet (DS39632D), 2007 [10] Microchip, MCP2551 – High-Speed CAN Transceiver Data Sheet (DS21667D), 2003 [11] Microchip, MCP201 – LIN Transceiver with Voltage Regulator Data Sheet (DS21730F), 2007 [12] Microchip, MCP2515 – Stand-Alone CAN Controller With SPI™ Interface Data Sheet (DS21801B), 2003 [13] Linear Technology, Wide Input Range, High Efficiency, Step-Down Switching Regulator Data Sheet, 1998 [14] Luigi Lugmayr, New Sony XEL-1 OLED TV (URL) [web page], Oct 1 2007; [last accessed Dec 10 2007] [15] VIA, VIA Eden® Processors - Low Power Fanless Processing (URL) [web page]; [last accessed Dec 10 2007] [16] Various Authors, Wikipedia – Windows CE (URL) [web page], last updated Dec 5 2007; [last accessed Dec 10 2007] [17] Various Authors, PGMFI.org – Library (URL) [web page], 2007; [last accessed Dec 10 2007] [18] Dalas - Maxim, DS18S20 High-Precision 1-Wire Digital Thermometer Data Sheet, Feb 21 2003

124