AutoPlug

128
Phase 2 Report Team 2 University Of Pennsylvania School of Engineering and Applied Science Department of Electrical and Systems Engineering ESE 450/451 Senior Design AutoPlug: Open Architecture for Automotive Services Ross Boczar [email protected] Gabriel Torres [email protected] Jason Suapengco (CIS) [email protected] 6 May 2011 Advisor: Dr. Rahul Mangharam, mLab, University of Pennsylvania

description

AutoPlug

Transcript of AutoPlug

Page 1: AutoPlug

Phase 2 Report

Team 2

University Of Pennsylvania

School of Engineering and Applied Science

Department of Electrical and Systems Engineering

ESE 450/451 Senior Design

AutoPlug:

Open Architecture for Automotive Services Ross Boczar [email protected]

Gabriel Torres [email protected]

Jason Suapengco (CIS) [email protected]

6 May 2011

Advisor: Dr. Rahul Mangharam, mLab, University of Pennsylvania

Page 2: AutoPlug

1

Abstract:

The modern automobile features more software components and electronics than ever before.

These electronics are prone to error, however, and vehicle recalls in the U.S. in 2009 crossed

over 16 million, with several million due to software bugs [1]. Unfortunately, many of these

components (known as ECUs - Electronic Control Units) are ―black boxes‖—their internal states

are difficult to determine. This creates a dilemma for car manufacturers, as knowing the state of

the electronics and software of a car could enable them to make better decisions regarding recalls

and warranty management. There is a need to remotely diagnose, update and certify automotive

software for efficient warranty and safety management.

AutoPlug is an automotive ECU testbed to develop mechanisms and protocols for remote

diagnosis, programming and testing of future vehicles. The goal of AutoPlug is to allow car

manufacturers to better identify, characterize, and predict automobile software errors.

AutoPlug consists of three layers: the vehicle simulation layer, the ECU network layer, and the

middleware layer. The vehicle simulation layer, implemented in the open-source racing engine

TORCS, provides realistic data to the ECU network. The ECU network layer, which models

individual car systems, such as steering or anti-lock brakes, receives this data and applies to

typical control algorithms. The middleware layer controls the interconnections of the ECU

network and is responsible for acting as a gateway (via a user interface) between the

manufacturer and the ECU network. This layer provides the interface for re-flashing software,

diagnosing software errors, and gathering vehicle statistics.

Page 3: AutoPlug

2

Table of Contents

1. PURPOSE AND SCOPE .......................................................................................................... 4

2. INTRODUCTION..................................................................................................................... 6

3. DISCUSSION OF PREVIOUS WORK .................................................................................. 8

4. STRATEGIC PLAN/STRUCTURE ..................................................................................... 10

4.1 SYSTEMS APPROACH ..................................................................................................... 10

4.2 SYSTEM SPECIFICATIONS ............................................................................................ 17

4.3 HARDWARE AND SOFTWARE REQUIREMENTS ...................................................... 22

4.4 TEST AND DEMONSTRATION ...................................................................................... 26

4.5 SCHEDULE ........................................................................................................................ 29

5. RESULTS ................................................................................................................................ 33

5.1 SIMULATION .................................................................................................................... 33

5.2 ECU NETWORK ................................................................................................................ 34

5.3 MIDDLEWARE ................................................................................................................. 42

5.4 OVERALL SYSTEM ......................................................................................................... 44

6. LESSONS LEARNED ............................................................................................................ 47

7. EQUIPMENT NEEDS ........................................................................................................... 48

8. CONCLUSIONS AND RECOMMENDATIONS ................................................................ 49

9. NOMENCLATURE ................................................................................................................ 50

10. REFERENCES ...................................................................................................................... 51

11. BIBLIOGRAPHY ................................................................................................................. 53

12. FINANCIAL INFORMATION ........................................................................................... 54

13. ETHICS ................................................................................................................................. 55

13.1 DESCRIPTION OF LARGER CONTEXT ....................................................................... 55

13.2 ANALYSIS OF ETHICAL ISSUES ................................................................................. 55

13.3 ETHICAL RECOMMENDATIONS ................................................................................ 55

14. SOFTWARE DOCUMENTATION .................................................................................... 56

15. APPENDICES ....................................................................................................................... 57

A1 CODE FOR SOFTWARE MODULE “PEDALS” ............................................................ 58

A2 HARDWARE DIAGRAMS ............................................................................................... 107

A3 CONTROL DIAGRAMS ................................................................................................... 116

A4 ADDITIONAL GRAPHS ................................................................................................... 119

Page 4: AutoPlug

3

A4.1 EXAMPLE ABS/BRAKES OPERATION .................................................................... 119

A4.2 PATHOLOGICAL ABS/BRAKES OPERATION ........................................................ 121

A4.3 CABIN COMFORT CONTROLLER ............................................................................ 124

A5 DATASHEETS .................................................................................................................... 125

A6 MATHEMATICAL EQUATIONS ................................................................................... 126

A7 ADDITIONAL SCREENSHOTS ...................................................................................... 127

Page 5: AutoPlug

4

1. PURPOSE AND SCOPE

Modern automobiles have become reliant on electronics in order to operate. Traditionally, the

typical car did not employ the use of complex electronics in order to operate, making most of its

operations completely mechanical. Today, as electronic components become ubiquitous in

automobiles, manufacturers must take into account faults of design and operation in both the

electronics and mechanical aspects of the car. What this project addresses is the need for

manufacturers to efficiently identify and resolve both software and hardware errors across an

existing customer base. In order to achieve this, the project scope was to design and implement

the following:

● A basic network of ECUs (Electronic Control Units), connected together using the CAN

(Controller Area Network) protocol. While each ECU controls a specific function of a

car, the network itself represents the basic components of a car, such as:

○ Throttle

○ Anti-Lock Brakes

○ Steering

○ Transmission

○ Cruise Control

● Integration of the ECU network into an automobile simulation model. This was

accomplished using the TORCS open-source car simulation engine. The TORCS car

model was used to feedback simulated data to the ECU network.

● A ―middleware‖ layer for both the verification of ECU network design as well as a user

interface to achieve the necessary goals.

With the use of these systems, the project achieves the following goals:

● Remote Diagnostics: Manufacturers are able to interface with a vehicle remotely and

analyze ECU data to determine what is wrong with the car. Bad sensor data can point

towards a mechanical malfunction and the on-board diagnostic system can warn the

driver about errors with more accuracy and specificity.

● Data Logging: Historical data gathered from vehicles using AutoPlug can be used to

predict whether errors will occur in the future. An example of which could be degraded

performance of a certain component that could lead to more serious issues.

● ECU Firmware Upgrades: Software errors can be fixed by deploying new firmware, in

the event of software bugs. This can be done remotely (for non-critical components), or at

a dealership (for critical components). ECUs are currently replaced instead of

reprogrammed in the event of a software malfunction.

● Recall Management: a manufacturer is able to tell which cars are affected by a recall by

simply accessing the CAN data that the middleware layer stores. Using this data, a

manufacturer can both identify the parts that are in each vehicle and alert the consumer in

the event of a recall.

Page 6: AutoPlug

5

This project did not consist of designing the electronic bare-bones of a car accurately. Such a

design would take years to complete, and it was not necessary for our project goals. The system

did need to maintain the characteristics of a modern vehicle electronic system, such as the use of

the CAN protocol and individual ECU hardware. Without the use of standard real world

components in our design, the project would be useless to our audience, as manufacturers would

have to redesign the whole automobile in order to take advantage of our results.

Another distinction that needs to be made is that some of the components that were represented

in the project design deal with safety-critical applications. We recognize that there are both

safety and privacy concerns associated with the final implementation of such a system, but the

project focus remained on the implementation of a functioning product, and not on privacy and

security concerns.

In order to verify the success of the project, we replicated a series of scenarios in which each of

our design goals was tested. A ―bug‖ (software error) was introduced into the system that the

middleware layer detected. This bug was in the form of incorrect operation of certain ECUs that

was corrected using the ECU upgrades capabilities of the system.

In order to verify the validity of the ECU network, the middleware layer provided visualizations

that corresponded to the behavior of the simulations. This proved that the ECU network was

behaving correctly and reporting the correct information.

Page 7: AutoPlug

6

2. INTRODUCTION

Due to the increase of electronic sub-systems within a modern vehicle, the amount of repairs due

to errors in both design and operation of those sub-systems has been increasing in an alarming

rate. Most new vehicles in the market are advertised to use drive-by-wire technology for

operation, which means that there is no longer any mechanical control from the user‘s input to

the actual operation of the car [2]. Modern vehicles are mostly controlled by computers, who in

turn take inputs from a driver. A typical modern car will include 70-100 ECUs (Electronic

Control Units), each controlling a specific function of the vehicle. These ECUs contain a total

estimate of over 100 million lines of code [3]. As a point of reference, Microsoft‘s Windows XP

contained about 40 million lines of code, when it was released in 2001 [4]. Due to this reliance

on electronics, automobile repairs are no longer limited to mechanical problems, with repairs due

to electronic or software bugs becoming more widespread. Since virtually all software contains

bugs, the automotive industry has had to adapt to this increase by employing more rigorous tests

and design paradigms. Nevertheless, software bugs are unavoidable. Some of the software

written by NASA‘s Software Assurance Technology Center, which is some of the best in the

industry, contains about one error per 10,000 lines of code. In the software industry, the number

of software bugs is closer to 20 per 1,000 lines [4]. By extrapolating this number it is easy to see

that car manufacturers have a daunting task to deal with when addressing automobile software

functions.

The AutoPlug system assists manufacturers in this area, by providing an efficient way to correct

software problems after release. In 2009, vehicle recalls in the US crossed the 15 million mark,

representing a large cost to manufacturers [1]. While the exact number of recalls due to software

errors is not available, some individual data from specific manufacturers is, with the total number

of recalls due to software errors in several millions.

AutoPlug consists of three layers: simulation, ECU, and middleware. The simulation layer

models a real automobile (1999-2001 Mitsubishi Lancer EVO VI), which provides a form of

verification for the ECU network. The ECU network consists of several micro-controllers, each

of which performs a specific function (e.g. steering, locking/unlocking doors, changing gears).

These micro-controllers are networked together using the industry standard CAN protocol. The

CAN protocol is used in virtually all modern automobiles as a means of communication between

ECUs [5]. Some functions of vehicles, such as Anti-Lock Braking System, require several ECUs

to work together in order to perform the necessary tasks, thus there is a need for them to

communicate. The ―middleware‖ layer consists of a small computer that provides a gateway for

the vehicle manufacturers to interface with the ECU network.

These three systems allowed us to implement the features outlined in the previous section:

● Remote Diagnostics: Manufacturers are able to interface with a vehicle remotely and

analyze ECU data to determine what is wrong with the car. Bad sensor data can point

towards a mechanical malfunction and the on-board diagnostic system can warn the

driver about errors with more accuracy and specificity.

Page 8: AutoPlug

7

● Data Logging: Historical data gathered from other vehicles using AutoPlug can be used

to predict whether errors will occur in the future. An example of which could be degraded

performance of a certain component that could lead to more serious issues.

● ECU Firmware Upgrades: Software errors can be fixed by deploying new firmware, in

the event of software bugs. This can be done remotely (for non-critical components), or at

a dealership (for critical components). ECUs are currently replaced instead of

reprogrammed in the event of a software malfunction.

● Recall Management: a manufacturer is able to tell which cars are affected by a recall by

simply accessing the CAN data that the middleware layer stores. Using this data, a

manufacturer can both identify the parts that are in each vehicle and alert the consumer in

the event of a recall.

Remote diagnostics is an important step in the evolution of vehicle repair. The current paradigm

consists of the user detecting unusual behavior, taking the vehicle in to the mechanic, being

quoted an amount for the repair and finally paying the mechanic for work done. A system of

remote diagnostics allows a consumer to get up to date reports on the state of their car, avoiding

an unnecessary trip to the mechanic and additional costs. Even more useful is the ability for car

manufacturers to accurately detect which cars are affected by a problem in the event of a recall.

As it stands now, automotive companies frequently recall more cars than they need to because

they have no way of knowing which cars happen to be affected by a problem[6]. This results in

large costs and unnecessary trips to a dealership.

Preemptive maintenance goes hand in hand with remote diagnostics. Major vehicle faults are

sometimes due to negligence and improper maintenance at the hands of the user, be it due to

ignorance or other causes. The manufacturer can remotely analyze the data provided by the

ECUs and alert the consumer before a minor issue becomes more serious.

Firmware upgrading is also an important feature of AutoPlug, allowing car manufacturers to

deploy new firmware for ECUs without the need to replace the units. The current method of

repairing electronic control units consists of replacing them with a new one. Mechanics simply

have no other way to do so [3]. This costs car manufacturers and users large amount of money

due to unnecessary replacement parts.

Page 9: AutoPlug

8

3. DISCUSSION OF PREVIOUS WORK

The motivation behind creating an automotive ECU test-bed with mechanisms for remote

diagnosis and software management is based on the idea of the ―car as a platform‖ referenced in

[7] as well as other sources. We will first examine projects whose goals are similar to that of this

report. A paper on AutoSar, a project dedicated to creating a standard for an automotive

architecture, states how the introduction of an industry wide standard is necessary and will open

new and different business opportunities for OEMs (Original Equipment Manufacturers) and

their suppliers [8]. As a collaboration of many different manufacturers (BMW, Bosch,

Continental AG, Chrysler, Ford, GM, Toyota, and Volkswagen), the goals of this paper can be

seen as profitable for these companies. With the completion of an architectural standard

(AutoSar), said companies can potentially purchase hardware from different vendors. On the

surface, AutoSar appears to be very similar to what we aim to do in this project. However, the

focus of our project is not to standardize the electronic hardware of a vehicle, but rather to

implement a system in which our goals are feasible. The ECU test-bed is simply a means to

demonstrate that the features described are possible and should be implemented in future

automobiles. Since an automotive electronic test bed standard has not yet been developed,

relevant work will be examined for each component of the project.

Vehicle Simulation Layer

Vehicle dynamics simulation could be considered its own industry within automobile design.

Many commercial off-the-shelf packages exist for simulating real-time motion of automobiles.

CarSim, rFactor, and ADAMS/Car are some of the vehicle simulation suites that have the ability

to integrate with controller models for real-time simulation.

Initially, the focus of this layer was to design a simulator in Simulink, a control systems design

suite. Though attempts were made using literature on different approaches to vehicle dynamics

simulation, including multi-body [9] and analytical models [10], the decision was made to

instead use the open-source racing and simulation engine TORCS.

The TORCS program includes a physics simulation engine to model car dynamics, although it is

not as nearly as accurate or detailed as commercial packages as CarSim. However, its open-

source architecture and price (free) made it the most sensible option for this project.

Models of additional vehicle components and ECU controllers (such as the engine, Anti-lock

braking system, or steering control) will need to be integrated into the TORCS engine. There

exist many examples of these systems, such as the system described in [11], and these will be

pieced together and possibly modified to fit into the overall automobile model. However, these

controllers would most likely need to be modified in order to work in our system.

Page 10: AutoPlug

9

Middleware Layer

There are implementations of existing systems, such as GM‘s OnStar, that perform similar

functions to what we aim to achieve, such as remote servicing [11]. These systems do not

perform firmware upgrades nor allow for direct remote management of the firmware. In contrast,

these programs are company specific and do not adhere to a standard across manufacturers. The

diagnostic and upgrade system of this project would be available for cars not outfitted with an

OnStar type system. Although OBD-II (OnBoard Diagnostics) ports are not installed in all cars,

they have become federally mandated in the U.S. and as new vehicles replace older ones, the

OBD-II port will be available in most vehicles. There has also been development concerning

high-level systems in a car, such as Microsoft‘s Blue&Me in-car entertainment system which

integrates several high-level media units of the car like a cell-phone and speaker system.

AutoPlug is at a lower-level than systems such as Microsoft‘s Blue&Me. Therefore, Microsoft‘s

and other systems can still operate within the electronic test-bed. Research has also been done

that proposes a method of updating the software on the ECU in C++ [12]. Although these

proposals have been made, they have yet to be carried out. With an electronic test-bed in place, it

is more efficient to update ECU software as the system for updating would be specified to the

test-bed and would not be vehicle-specific.

ECU-CAN Network

Several papers have discussed the implementation of an ECU network using the standard CAN

protocol, some have even gone as far as showing how the security of such a network is

compromised. As [7] has shown the ease at which the modern vehicle can be controlled and

attacked (successfully) using remote tools is quite high. Although, they did not create an ECU

test bed, but used an actually vehicle in their security attacks, their setup is similar to what we are

implementing. By connecting to the OBD-II port, they were able to obtain read/write access to

the ECU network of the vehicle. Although security considerations are out of the scope of this

project, it may be possible to upload firmware on the car with better security in the future. In

terms of the automotive electronic test bed, there has been much research concerning each

individual ECU. Such examples are research that looks into the software architecture for the

ECU controlling the manual transmission [13] and research concerning the ECU controlling the

rear wheel steering system [14]. Although this research focuses on the individual unit, it does not

encompass than entire ECU network. Research has been done concerning optimizing CPU usage

across ECUs while meeting time-constraints [15].This paper reveals that it may be possible to

use fewer processors to run jobs while matching the required time constraints by utilizing the

processors in an effective manner. It is important to keep in mind this idea of a time constraint in

the ECU test bed in order to ensure safe functioning of the car. In addition to research about job

scheduling across CAN, there can be job scheduling in an ECU [16]. This research uses ECUs

ported to an OSEK real time operating system (RTOS) - similar to this project‘s. Using OSEK,

job speeds are reported and the time it takes to switch tasks are recorded. The results show that

the OSEK RTOS was able to complete the many tasks required of an ECU in an automobile in

an efficient manner.

Page 11: AutoPlug

10

4. STRATEGIC PLAN/STRUCTURE

Section 4 outlines the specifications and operation of both the abstract high-level system and its

individual subsystems.

4.1 SYSTEMS APPROACH

At the most abstract level, AutoPlug can be viewed as the interconnection of three different

layers: the simulation layer, the ECU network layer, and the middleware layer.

Figure 4.1-1 illustrates the connections between the three layers. Simulated control inputs are

passed to the car simulation model. The model then outputs simulated sensor data about the car

to a network of microcontrollers representing the ECU network. The ECU network and the

middleware layer then work together to process data and make decisions about the car's

operation, which are then sent back to the running simulation (Figure 4.1-2). As Figure 4.1-1

shows, both the simulation and middleware layers interface with the ECU network, which in turn

takes input from a user.

Figure 4.1-1 High-Level Overall System Diagram

Page 12: AutoPlug

11

Figure 4.1-2 Mid-Level System Diagram

Page 13: AutoPlug

12

4.1.1 Simulation Subsystem

The core of the simulation subsystem was a real-time simulation of an automobile using the

racing/simulation engine TORCS (Figure 4.1.1-1). Since our project by nature was the

development of an open-source architecture, we needed to use an ―open‖ car simulation model,

as having to reverse-engineer an actual car in order to interface it with the other components of

our architecture was the exact problem we were trying to avoid.

Figure 4.1.1-1 Simulation Subsystem

The TORCS model simulated car dynamics through physics-based modeling, as well as

individual car subsystem components (engine, suspension, steering system). However,

additional code needed to be added in order to support some ECU network functions. This code

included modeling additional vehicle components, as well as integrating the data acquisition

board into the simulation in order to provide real-time inputs and outputs. Since TORCS was a

free open-source program, we were at the mercy of the developers in terms of model accuracy.

TO EC

U

Page 14: AutoPlug

13

The TORCS online community was solely responsible for the fidelity of the simulation.

However, for the purposes of our project, we believed that the TORCS model was sufficient to

show feasibility of the overall system. The TORCS simulator provided the following features

that we deemed essential to the feasibility of our project (including but not limited to):

Realistic tire dynamics based on the Pacejka tire model, an industry-standard empirical

tire model

Variable road conditions

Accessible physics engine outputs for use in ECU network (e.g. yaw rate, wheel speeds,

later acceleration)

Suspension and differential modeling

The main alternative to TORCS was the industry-standard CarSim, a high-fidelity simulator.

However, the cost of CarSim was prohibitively high (upwards of $8,000 for an academic license)

and was a closed-source program, which would not have afforded us the flexibility to make the

previously mentioned changes in the code. Using the open-source TORCS model allowed the

design focus to be placed on the ECU network-middleware interaction, which was the central

focus of AutoPlug.

The parameters defining the TORCS car model were based on the 1999-2001 Mitsubishi Lancer

EVO VI. This car was chosen as the representative model for our project as its real-life

counterpart included many of the software-based systems we intended to model (ABS, stability

control, active differential control).

Also included in the simulation subsystem was a block representing a visualization of the

simulation data. This represents the TORCS visualization screen (Fig. 4.1.1-3), which aided in

model verification and demonstrated correlation between simulated ―real-world‖ data involving

the car and the processed data displayed by the middleware layer visualization.

Page 15: AutoPlug

14

Figure 4.1.1-3 TORCS Visualization

4.1.2 Simulation - ECU Network Connection:

The interface between the TORCS car simulation and the microcontroller ECU network was

implemented using a data acquisition card (DAQ) on the host computer. This card provided both

analog and digital I/O for transmission of data between the two layers. We used two National

Instruments cards (model NI-6229-M) with four connector blocks.

4.1.3 ECU Network Subsystem

The ECU network subsystem consisted of individual Freescale MC9S12 micro-controllers that

perform each specific function within a vehicle. Figure 4.1.3-1 shows a general interface

between the ECUs and the CAN network. As can be seen from the figure, each ECU connected

the network in parallel, with every ECU able to receive the messages that are passed through the

circuit. CAN-HIGH and CAN-LOW are the two rails that make up the CAN bus. The ECUs had

Page 16: AutoPlug

15

built in CAN transceivers and thus could connect directly to the CAN bus. The inputs/outputs on

the figure are not exhaustive and only make up the CAN interface connections.

Figure 4.1.3-1 ECU Network Subsystem

Individual ECUs varied by design depending on their function, but most of them consisted of a

connection to the CAN network, inputs from the DAQ board and the corresponding output back

to the DAQ. Inputs were generally analog, which had to be converted into digital signals for

processing. The outputs of the ECU refer to both the interface to the CAN and the outputs to the

actuators, which were simulated using TORCS. An example, Figure 4.1.3-2 shows the hardware

diagram for the transmission ECU. In this example, all inputs and outputs are digital. For more

specific designs, please refer to the diagrams in the result section.

120 Ohms 120 Ohms

Page 17: AutoPlug

16

Figure 4.1.3-2 ECU Design Model (Transmission)

4.1.4 ECU Network – Middleware Connection:

The individual ECUs only interfaced with the middleware through the CAN bus. Refer to section

4.2.2 for how they were connected.

4.1.5 Middleware Subsystem

The middleware subsystem consisted of standard computer running Linux. At the design stage of

this project, we planned on using a small single board computer called the ―BeagleBoard‖ to

perform all of our middleware functions. Due to speed and power constraints, we fell back on

this plan and used a standard laptop instead. All of the design and code would work on any

computer that supports the Linux OS and has a USB port, so a faster and more expensive version

of the BeagleBoard could work in the future.

The middleware computer listened to the CAN bus to store and process relevant information, and

acted as a gateway for the vehicle manufacturers to take advantage of the following features:

Vehicle Visualizations: Acts as a dashboard to display vehicle state. This corroborates the

simulation as well as the ECU network.

Remote Diagnostics: Contains routines that perform diagnostics for each ECU. It simply

uses the CAN messages that are received and analyzes them. This could be done locally

or remotely by the manufacturer.

ECU Upgrades: ECU upgrade interface for remote upgrades through the CAN bus.

5V

Pin 1 – Vaux

Pin 3 – GND

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL

Pin 55 – PB0

Pin 51 – PB2

Pin 53 – PB1

Pin 49 – PB3

Pin 45 – PB5

Pin 47 – PB4

GEAR_2 FROM TORCS

GEAR_0 TO TORCS

GEAR_2 TO TORCS

GEAR_1 TO TORCS

GEAR_0 FROM TORCS

GEAR_1 FROM TORCS

Page 18: AutoPlug

17

4.2 SYSTEM SPECIFICATIONS

The overall system consisted of a combination of the three subsystems that have been previously

described. The final system interfaced the ECU Network with both the simulation layer and

middleware layer to create a ―virtual car‖ in which the user (an individual who the project is

being presented to) could actively drive and input different settings to a simulated car.

In other words, the overall system behaved as if it were a car, only in simulation interfaced with

the ECU network. The system is best described the Table 4.2-1.

Table 4.2-1

Inputs Simulation Response Middleware Response

Steering Car Turning Steering Angle Reported

Brakes Car Braking, Brake Lights On Brake Alert

Accelerator Car Acceleration Increased Speed, Fuel

consumption

Shifter Transmission Shift Gear change reported

Cruise Control Constant Velocity Report Cruise Control Mode

Trans Mode (Man. To Auto) None (Dependent on ECU) Report Transmission Mode

Lights Turn Headlights on Report Light status

Engine Mode (Sport v. Econ) Different shift points Report Engine mode

The user can also use the middleware layer to interface with the vehicle. The middleware layer

will allow the running of diagnostic functions, data logging as well as reprogramming an ECU

through the CAN bus. Through the middleware layer, the user is able to explore the different

features that were implemented in the project, such as:

Table 4.2-2

Middleware Function Middleware Function Description

Car State Information Displays Speed, RPMs, Fuel level. Car state

information should match up with simulation

characteristics.

Remote Diagnostics ECU data used for identifying possible

malfunctions.

Remote ECU Flashing An ECU can be reprogramed without removal.

An interface in the middleware layer allows for

this.

Data Aggregation (Statistics Gathering) Info on past trips is available. Data logging can

be enabled at will and can store all information

that is being transferred in the CAN bus.

4.2.1 Simulation Subsystem

● Open-source car model provided in TORCS racing/simulation engine (Linux); will be

modified in order to support ECU network functions

Page 19: AutoPlug

18

● Model type: 1999-2001 Mitsubishi Lancer EVO VI (in order to capture high-end

ECU features)

● Mixed continuous/discrete model (hybrid system); simulation timestep: 0.002s

● Simulated using TORCS engine, interfaced with the DAQ board

● Uses C API (Application Programming Interface) for the DAQ, using the NI

DAQmx driver

● NI DAQ board (PCI 6229 M Series, SCB 628 Connector Block)- interfaced with

TORCS

● Max sample rate: ~50kHz (1 channel)

● 2 boards running in parallel

● Provides analog and digital I/O, as well as counter I/O (for Pulse Width

Modulation [PWM] signals)

● Simulation visualization

● TORCS racing visualization

● Used to show correlation with ―dashboard‖ visualization running with the

BeagleBoard

● Data outputs included: accelerometer data, cabin control data, engine, user controls,

steering input, gas pedal/brake input (see Section 4.3.3 for complete list)

4.2.2 ECU Network Subsystem

Each ECU was implemented using an HCS12 microcontroller (MC9S12C128 variant). The

controllers were supplied by the University and were manufactured by Axiom Manufacturing

(internal model: APS12C128).

Implemented ECUS:

Steering

o Provided steering input through electronic wheel, as well as buttons for manual

shifting and cruise control

Pedals

o Provided input for accelerating/braking by analog pedals

Cruise Control

o Controlled car speed when enabled to match set speed

Transmission

o Changed gears automatically or manually depending on user selection

Anti-Lock Brake System (ABS)/Brakes

o Reduced skidding when brakes were applied quickly

Cabin Comfort

o Allowed user to maintain virtual cabin temperature

Engine

o Reported RPM and fuel level data

Differential Control

Page 20: AutoPlug

19

o Reduced oversteer/understeer (turning rate or yaw rate instability)

Console

o Provided switches for virtual car lights as well as switching between transmission

and engine modes

Table 4.2.2-1 and Table 4.2.2-2 describe the physical and electronic inputs and outputs for each

ECU in the ECU network. The CAN messages are the internal software names for the signals

being sent over the CAN network, detailed in Section 4.3.3.

Table 4.2.2-1 ECU Signal Specifications

ECU NAME

MIDDLE

-WARE

ID

INPUTS FROM

TORCS DAQ

OUTPUTS TO

TORCS DAQ A/D INPUTS (OTHER)

Cruise

Control 0x0D Vehicle speed

ABS/Brakes 0x0E

Linear wheel

speeds x 4

Individual brake

commands x 4

Transmission 0x06

Transmission

gear

Transmission gear

command

Pedals 0x04

Accelerator

commands

Accelerator pedal, brake

pedal

Steering 0x05 Steering angle

Shift buttons, cruise control

set/reset buttons, steering

wheel angle

Engine 0x03 Engine RPM

Cabin Control 0x0A

Cabin

temperature Fan power

Differential 0x0C Yaw rate error Headlight,brakelight

Console 0x0B

Headlight command,

brake light

command

Headlight switch,

transmission mode switch,

engine mode switch

Page 21: AutoPlug

20

Table 4.2.2-2 ECU CAN Specifications

ECU NAME CAN INPUTS CAN OUTPUTS

Cruise Control cruiseModeMsg

cruiseAccelMsg,

vehicleSpeedMsg

ABS/Brakes

vehicleSpeedMsg,

pedalMsg

wheelSpeedMsg, ABSMsg,

TracMsg, brakesAppliedMsg

Transmission

vehicleSpeedMsg,

shiftMsg, transMsg,

engineMsg transMsg

Pedals

cruiseAccelMsg,

cruiseModeMsg,

TracMsg pedalMsg, cruiseModeMsg

Steering

cruiseModeMsg, shiftMsg,

steeringMsg

Engine accMsg engineMsg

Cabin Control tempMsg, tempRefMsg

Differential

ABSMsg,

vehicleSpeedMsg,

steeringMsg diffMsg, yawErrorMsg

Console pedalMsg

accMsg, transMode,

engineMsg

Design Decisions:

For individual ECU implementations, we chose to use an HCS12 variant (MC9S12C128). The

reason of us choosing the HCS12 is due to the fact that Freescale is a leading manufacturer of

microcontrollers for vehicle electronics [17].

Most cars employ the use of two or more CAN buses in order to operate. For our purposes, we

chose to only use one CAN bus. The HCS12 microcontroller variant that we have does not

support more than one CAN bus. If we were to use two CAN buses for our design, some ECUs

would be isolated from others, preventing them from communicating with each other.

Page 22: AutoPlug

21

Figure 4.3.2-1 ECU Network Spec

CAN Network:

The CAN network itself consisted of two rails, which were terminated at both ends using 120

Ohm resistors. The onboard CAN controllers on the HCS12 are PCA82C25 physical interfaces.

While this controller is rated to support up to 110 nodes, we hit a limit of 10 nodes due to some

undetermined characteristic of our implementation. Increasing the resistance of the CAN bus

helped with the problem but it was more of a quick fix than a solution.

The CAN bus that we ended up using for the system consisted of a single 500Kbits bus that

connected with all of the ECUs as well as the middleware layer.

4.2.3 Middleware Layer Subsystem

The middleware layer consisted of a standard computer running Ubuntu Linux. As was

mentioned earlier, we implemented most of the system on a single board computer but due to

performance limitations chose to use a standard laptop for the middleware layer.

In order to communicate with the CAN bus, the middleware used a PEAK CAN-USB adapter.

Using APIs supplied by PEAK, the CAN-USB adapter converts CAN bus data into a format that

is easy to work with.

Page 23: AutoPlug

22

4.3 HARDWARE AND SOFTWARE REQUIREMENTS

4.3.1 Hardware Requirements and Design Approach

4.3.1.1 Simulation Hardware

The TORCS simulation required a data I/O method for communicating with the ECU network.

The NI DAQ board provided ample digital and analog I/O for this task. Using appropriate

send/receive/pack/unpackcode in the TORCS model, the simulated car communicated through

the DAQ board. The analog sample rate, 1 kHz, was determined by the complexity of the

TORCS model modifications and the amount of ECU‘s interfaced with the model.

The simulation computer needed to be relatively fast (3 GHz, 64-bit, 2GB RAM) in order to

effectively compute a car model while sampling from the DAQ board. It also required empty

PCI Express slots in order to facilitate the NI DAQ board.

4.3.1.2 ECU Hardware

Each ECU was represented by an HCS12 microcontroller (MC9S12C128 variant). The datasheet

can be found in the bibliography section, but a short description is included here:

• 16-bit HCS12 CORE

— HCS12 CPU

— MMC (memory map and interface)

— INT (interrupt control)

— BDM (background debug mode)

— DBG12 (enhanced debug12 module including breakpoints and change-of-flow trace buffer)

— Multiplexed Expansion Bus (available only in 80 pin package version)

• 16-bit HCS12 CPU

— Upward compatible with M68HC11 instruction set

— Interrupt stacking and programmer‘s model identical to M68HC11

— Instruction queue

— Enhanced indexed addressing

• Wake-up interrupt inputs

— Up to 10-port bits available for wake up interrupt function

• Memory options

— 16K, 32K, 64K, 96K and 128K Byte Flash EEPROM (erasable in 512-byte sectors) or

— 16K, 32K, 64K, 96K and 128K Byte ROM

— 2K and 4K Byte RAM

• Analog-to-Digital Converters

— One 8-channel module with 10-bit resolution.

— External conversion trigger capability

• Up to one 1M bit per second, CAN 2.0 A, B software compatible modules

— Five receive and three transmit buffers

Page 24: AutoPlug

23

— Flexible identifier filter programmable as 2 x 32 bit, 4 x 16 bit or 8 x 8 bit

— Four separate interrupt channels for receive, transmit, error and wake-up

— Low-pass filter wake-up function

— Loop-back for self test operation

• Timer Module (TIM)

— 16-bit Counter with 7-bit Prescaler

— 8 programmable input capture or output compare channels

— Simple PWM Mode

— Modulo Reset of Timer Counter

— 16-Bit Pulse Accumulator

— External Event Counting

— Gated Time Accumulation

• 6 PWM channels

— Programmable period and duty cycle

— 8-bit 6-channel or 16-bit 3-channel

— Separate control for each pulse width and duty cycle

— Center-aligned or left-aligned outputs

— Programmable clock select logic with a wide range of frequencies

— Fast emergency shutdown input

• Serial interfaces

— One asynchronous serial communications interface (SCI)

— One synchronous serial peripheral interface (SPI)

Communication via CAN was achieved using an onboard PCA82C25 CAN Transceiver. This

device supported speeds of up to 1Mbps and supported up to 110 nodes.

4.3.1.3 Middleware Hardware

The middleware consisted of a standard computer running Ubuntu Linux as well as a USB to

CAN interface:

HP Envy 14

PEAK CAN-USB (IPEH-002021) – USB to CAN adapter for interfacing with the CAN network

4.3.2 Software Requirements and Design Approach

4.3.2.1 Simulation Software

The car simulation required TORCS and appropriate Linux libraries. The NI DAQ board requires

the installation of the NI DAQmx driver software.

Page 25: AutoPlug

24

4.3.2.2 ECU Software

The individual ECUs ran C code created using the Codewarrior IDE 4.7. The compiler included

in the Codewarrior suite was the in-house compiler created by Freescale.

4.3.2.3 Middleware Software

The middleware ran on Ubuntu 9.10 (Karmic Koala). Most of the codebase for the middleware

was coded in C, using the following APIs:

-GTK+ For Dashboard visualization

-PEAK CAN for CAN bus communication

-Glib2

-Loudmouth API

-GNU Plot

-Standard C libraries

4.3.3 Interface Control Documents

Table 4.3.3-1 details the messages sent between the ECU network and the middleware layer. All

messages were unsigned 8-bit integers, unless otherwise noted. The unit ‗TORCS‘ corresponds

to TORCS commands being normalized to 1.0, scaled to 100 in our code (e.g. accelCmd=100

corresponds to accel=1.0 in the TORCS code, which is full acceleration).

Page 26: AutoPlug

25

Table 4.3.3-1 CAN Message Descriptions

CAN Message Description

CAN ID

(.byte) Units

Range

(Integer) Notes

vehicleSpeedMsg Vehicle speed 0x03 km/h [0,255]

pedalMsg.brakeCmd Brake pedal 0x04 TORCS [0,100]

steeringMsg Steering angle 0x05 proportional [10,90] [10,90] = +/- 135 degrees

engineMsg.engineRPM Engine RPM 0x06.1 proportional [0,255] [0,255] = 0-9000 RPM

engineMsg.fuel Engine fuel level 0x06.2 L*10 [0,255]

engineMsg.fuelmode Engine mode 0x06.3 sport/econ [0,1] 0=sport, 1=economy

pedalMsg.accelCmd Accelerator pedal 0x07 TORCS [0,100]

cruiseModeMsg Cruise control mode 0x08 on/off [0,1] 1=enabled

cruiseAccelMsg

Cruise control

acceleration 0x09 TORCS [0,100]

shiftMsg Manual shift command 0x0A up/down [0,2] 0=downshift, 2=upshift

transMsg.gear Transmission gear 0x0B.1 gear [0,7] Value is current gear +1

transMsg.shiftmode Transmission Mode 0x0B.2 auto/manual [0,1] 0=automatic, 1=manual

wheelSpeedMsg.wheelSpeedFL

Linear wheel speed

(FR) 0x0C.1 km/h [0,255]

wheelSpeedMsg.wheelSpeedFR

Linear wheel speed

(FL) 0x0C.2 km/h [0,255]

wheelSpeedMsg.wheelSpeedRL

Linear wheel speed

(RR) 0x0C.3 km/h [0,255]

wheelSpeedMsg.wheelSpeedRR

Linear wheel speed

(RL) 0x0C.4 km/h [0,255]

brakesAppliedMsg.FR

Applied brake cmd.

(FR) 0x0E.1 TORCS [0,100]

brakesAppliedMsg.FL

Applied brake cmd.

(FL) 0x0E.2 TORCS [0,100]

brakesAppliedMsg.RR

Applied brake cmd.

(RR) 0x0E.3 TORCS [0,100]

brakesAppliedMsg.RL

Applied brake cmd.

(RL) 0x0E.4 TORCS [0,100]

ABSMsg.FR ABS cmd. (FR) 0x0E.5 TORCS [0,100]

ABSMsg.FL ABS cmd. (FL) 0x0E.6 TORCS [0,100]

ABSMsg.RR ABS cmd. (RR) 0x0E.7 TORCS [0,100]

ABSMsg.RL ABS cmd. (RL) 0x0E.8 TORCS [0,100]

TracMsg

Traction control

message 0x0F TORCS [0,100] Not fully tested

AccMsg Console settings 0x18 - -

bits:

b00000(fuel)(brklight)(headlight)

fuelmode: 0=sport, 1=economy

lights: 0=off, 1=on

DiffMsg Torque split command 0x20 N*m [-50,50] signed 8 bit

YawErrorMsg Yaw rate error 0x21 proportional [-127,128] signed 8 bit

[-127,128] = +/- 2.5 rad/s

tempMsg Cabin temperature 0x22 deg F * 2 [0,255]

tempRefMsg

Desired (set)

temperature 0x23 deg F * 2 [0,255]

Page 27: AutoPlug

26

4.4 TEST AND DEMONSTRATION

While our complete system was modular, with subsystems designed and developed in parallel,

many of the test setups consisted of collaboration between two sections, particularly the ECU

network and simulation layers. Section 4.4.1 outlines our test paradigms for each of the three

layers as well as the interfacing between them. Each layer had a subset of features that were

tested.

4.4.1 Test

4.4.1.1 Simulation Subsystem

To test the simulation subsystem, we provided input to the TORCS simulation via the ECU

network. This was accomplished using an electronic steering wheel and pedal, which were

routed to the appropriate ECUs. Oscilloscope measurements of DAQ input/output signals were

made in order to ensure:

1. Correlation of TORCS model behavior to user input.

2. Correlation of TORCS model to middleware output (―dashboard visualization‖).

Each individual ECU subsystem was first tested (at system rest), followed by testing small

subsets of related systems, followed by running a ―normal‖ simulation attempting to model

typical ECU usage.

4.4.1.2 Simulation – ECU Network Connection

There was an inherent connection between the design and testing of each ECU and its simulated

counterpart. Each ECU took inputs from the simulation layer and processed them, after which it

sent its own outputs back to the simulation layer for the simulation.

The DAQ I/O signals listed in Section 4.2 were measured to ensure they corresponded with the

desired input or output.

4.4.1.3 ECU Network

All ECUs were tested for common operations, such as CAN send/receive and analog signal I/O.

Each ECU had more complex functions that were tested using oscilloscope measurements or

verification of CAN data:

Pedals ECU:

Read pedal signals correctly

Report pedal signals correctly

Page 28: AutoPlug

27

Steering ECU:

Read steering wheel correctly

Report angle correctly

Correct button operation

ABS/Brakes ECU:

Read wheel speed signals correctly

Report brake command signals correctly

Correct PID controller operation

Differential ECU:

Read yaw rate error signals correctly

Report differential command signals correctly

Correct PID controller operation

Cruise Control ECU:

Read vehicle speed signals correctly

Report cruise acceleration signals correctly

Correct PID controller operation

Cabin Comfort ECU:

Read temperature signals correctly

Report fan power signals correctly

Correct PID controller operation

Transmission ECU:

Read gear signals correctly

Report gear command signals correctly

Correct shifting controller operation

Console ECU:

Read switches correctly

Report console signals correctly

Engine ECU

Read and report fuel and RPM signals correctly

4.4.1.4 ECU-Middleware Connection

This interface relied on a functioning CAN protocol. Once this was verified to be working, the

rest of the connections between the ECUs and the middleware connectionwere able to be realized

realized through CAN messages that can be reliably read.

Page 29: AutoPlug

28

4.4.1.5 Middleware Subsystem

The middleware subsystem served to verify the operation of the ECU network and implemented

the more complex functions of our system, which are essentially the main goals of the project.

Remote Diagnostics – The middleware layer was verified to be able to relay messages to the

ECUs and receive diagnostic data by checking the data sent over CAN with the data shown on

the diagnostics screen.

Statistics Gathering – The middleware layer was verified to be able to maintain a database

locally that stores CAN data for the potential application of analysis by vehicle manufacturers. In

order to test this, sample CAN data was sent on the network and verified with data saved in the

database.

4.4.2 Demonstration

The demonstration consisted of presenting system as it functions as a whole. The different

features of AutoPlug were demoed independently to illustrate their functionality. Additionally,

real-world scenarios illustrating the use of AutoPlug were demonstrated. These scenarios are

detailed in Section 5.4: Overall System.

Page 30: AutoPlug

29

4.5 SCHEDULE

Page 31: AutoPlug

30

Page 32: AutoPlug

31

Page 33: AutoPlug

32

4.5.1 Schedule Discussion

Most of the first semester was spent researching about the project and attempting to create proof-

of-concepts for each of the three subsystems. Once a final design was agreed upon,

implementation began at the end of the first semester and continued to the end of the year. Most

tasks were completed on schedule. However, there was slip on some tasks due to the expansive

nature of this system: some extraneous features needed to be scaled back or removed if time did

not permit for their completion. Nevertheless, the main design and implementation goals of

AutoPlug were successfully completed by Demo Day.

Page 34: AutoPlug

33

5. RESULTS

5.1 SIMULATION

5.1.1 DAQ/TORCS Integration:

The NI DAQ board was integrated into the code base of the TORCS simulation engine. We

created the ability in TORCS to query the DAQ board for inputs in order to receive data from the

ECU network, as well as to output simulation data to the appropriate ECUs. This was

accomplished through the use of the NI DAQmx driver, which is a C API containing functions

that control the DAQ board. The TORCS engine was modified in order to support the NI

DAQmx libraries.

Figure 5.1.1-1 DAQ/TORCS Integration Software Flow

TORCS updates each car state by means of a ―robot,‖ a segment of code that controls each car

(Fig. 5.1.1-1). We modified the robot to use the DAQ board to read and write data to and from

the ECU network. We could then provide real-time I/O between TORCS and each ECU.

5.1.2 TORCS Modifications

The following modifications to the TORCS code base were implemented in order to increase the

functionality of the TORCS simulation:

Added support for ECU-controlled active differential

Added engine hard shutoff switch for ignition simulation

Added support for individual brake commands for ABS (credit to Utsav Drolia, mLab)

Modified car visualization model for headlights and brake lights

Page 35: AutoPlug

34

5.2 ECU NETWORK

5.2.1 Controller Implementation

Each controller was implemented on a Freescale HSC12 microcontroller. The following sections

briefly describe their operations.

5.2.1.1 Cruise Control ECU Pseudocode:

1. Read analog vehicle speed signal.

2. If we have enabled cruise control via the steering wheel:

a. Compare to Vref, which corresponds to reference speed.

b. Compute output commands using PI feedback.

c. Send cruise control signals over CAN.

5.2.1.2 ABS/Brakes ECU Pseudocode:

1. Read analog linear wheel speed signals.

2. If the car is are braking and ABS is enabled:

a. Check to see if wheels are slipping.

b. If at least one wheel is slipping:

i. Compute ABS command using PID feedback.

ii. If the ABS has saturated the brake on at least one wheel:

1. Reset all PID controllers (pulsing).

c. Else, make sure the PID output is zero.

3. Else, make sure the PID output is zero.

4. Subtract ABS commands off of brake commands and limit to [0,100].

5. ABS Timeout:

a. If we have not enabled ABS in a while:

i. Make sure the PID output is zero.

6. Set output brake command PWM signals to corresponding duty cycle.

7. Send all brake data over CAN.

5.2.1.3 Cabin Control ECU Pseudocode:

1. Read analog cabin temperature signal.

2. Read analog desired cabin temperature setting.

3. Calculate temperature error.

4. Compute output commands using PID feedback.

5. Set fan power PWM signal to corresponding duty cycle.

6. Send fan power signal over CAN.

Page 36: AutoPlug

35

5.2.1.4 Console ECU Pseudocode:

1. Read headlight, engine mode, and transmission mode switches.

2. Output headlights and brake lights signals on digital port.

3. Send console signals over CAN.

5.2.1.5 Differential ECU Pseudocode:

1. Read analog yaw rate error signals.

2. If the car is moving fast enough and is turning enough:

a. If yaw rate error is large:

i. Compute ABS command using PID feedback.

b. Else, make sure the PID output is zero.

3. Limit differential message to [0,100] (corresponding to [-50 50]).

4. Set output torque split PWM signal to corresponding duty cycle.

5. Send differential data over CAN.

5.2.1.6 Engine ECU Pseudocode:

1. Read analog engine RPM signal.

2. Read digital fuel level signal on digital port.

3. Echo engine mode signal over CAN.

4. Send engine signals over CAN.

5.2.1.7 Pedals ECU Pseudocode:

1. Read analog pedal signals.

2. If pedals are engaged and cruise control is active, kill cruise control.

3. Else, set cruise control as per CAN message.

4. If cruise control is on:

a. Accelerator command = cruise accel. message.

b. Brake command = -(cruise accel.) if (cruise accel)<0;

5. Else, accel. and brake commands are pedal signals.

6. Set accelerator pedal PWM signal to corresponding duty cycle.

7. Send pedal signals over CAN.

5.2.1.8 Steering ECU Pseudocode:

1. Read analog steering angle signal.

2. Parse buttons for shift and/or cruise control signals.

3. Set steering PWM signal to corresponding duty cycle.

4. Send steering shift, and cruise enable signals over CAN.

Page 37: AutoPlug

36

5.2.1.9 Transmission ECU Pseudocode:

1. Read digital gear signals on digital port.

2. Update shift points depending on sport/economy mode.

3. Update transmission mode as per CAN message.

4. Wait for timeout (used to regulate shifting speed).

5. If a shift message has been received and the car is either in manual transmission, in

neutral/reverse, or is shifting down from first gear:

a. Update gear with shift message.

6. Else, compute gear based on vehicle speed and car parameters.

7. Set gear command signal on digital output port.

8. Send transmission signals over CAN.

5.2.2 Controller Results

The following sections give examples of controller operation using data logged by the

middleware layer, for the following ECUs which implemented controls algorithms:

Cruise Control

ABS/Brakes

Differential Control

Transmission Control

Cabin Comfort

5.2.2.1 Cruise Control Results

Figure 5.2.2.1-1 Example Cruise Control Operation

2 4 6 8 10 12

0

25

50

75

100

Time (s)

Ve

hic

le S

pe

ed

(km

/h)

Cruise Control Operation

2 4 6 8 10 12

0

10

20

30

Cru

ise

Co

ntr

ol A

cce

lera

tion

Co

mm

an

d (

no

rma

lize

d to

10

0)

Speed

Cruise Accel.

Page 38: AutoPlug

37

5.2.2.2 ABS/Brakes Results

Figure 5.2.2.2-1 Example ABS/Brakes Operation: Speed Comparison

Figure 5.2.2.2-1 Example ABS/Brakes Operation: Brake Pulsing (FR Wheel)

0

100

200ABS/Brake Operation: Vehicle vs. Wheel Speed

0

100

200

Sp

ee

d (

km

/h)

0

100

200

3 3.5 4 4.5 5 5.5 6 6.5 70

100

200

Time (s)

Vehicle

Wheel (FL)

Vehicle

Wheel (RR)

Vehicle

Wheel (RL)

Vehicle

Wheel (FR)

3 3.5 4 4.5 5 5.5 6 6.5 7

0

150

100

50

200

Time (s)

Whe

el S

peed

(km

/h)

ABS/Brakes Operation: Wheel Speed vs. Brake Command

3 3.5 4 4.5 5 5.5 6 6.5 7

0

50

100

25

75

App

lied

Bra

ke C

omm

and

(nor

mal

ized

to 1

00)

Wheel Speed (FR)

Brake Cmd. (FR)

Page 39: AutoPlug

38

The remaining wheels for this example are given in the Appendix A4-1

5.2.2.3 Differential Control Results

Figure 5.2.2.3-1 Example Differential Control Operation

5.2.2.4 Transmission Control Results

Figure 5.2.2.4-1 Example Transmission Operation

3 4 5 6 7 8 9

-60

-40

-20

0

Time (s)

Tor

que

Spl

it (N

*m)

3 4 5 6 7 8 9

-3

-2

-1

0

Yaw

Rat

e E

rror

( ra

d/s)

Differential Control Operation

Yaw Rate Error

Torque Split

0 2 4 6 8 10 12

0

50

100

150

Time (s)

Veh

icle

Spe

ed (k

m/h

)

Automatic Transmission Operation

0 2 4 6 8 10 12

1

2

3

4

5

6

Tra

nsm

issi

on G

ear

Gear

Speed

Page 40: AutoPlug

39

5.2.2.5 Cabin Control Results

Due to limitations of the CAN transceivers regarding maximum node count, we were not able to

retrieve the cabin control ECU data over the CAN network without error. However, we

implemented a model of the controller in Simulink, the results of which are shown in Appendix

A4-3.

5.2.3 CAN Boot-loader

The CAN boot-loader was implemented for the purpose of reprogramming ECU firmware

through the CAN bus. This allows the middleware to re-flash an ECU after it has been installed

on the vehicle. Figure 5.2.3-1 contains the program flow for the bootloader. The bootloader itself

sits in high memory (0xF000 and above). The boot loader accepts the following messages:

JMP to Boot message: LEN:2 ID:2 MSG: [ECUID 0x03]

Instruction message: LEN: 8 ID:1 MSG: [ADDRH ADDRL INS1 INS2 INS3 INS4

INS5 INS6]

Jump out of Boot message: LEN 8 ID:1 MSG: [0 0 0 0 0 0 0 0]

The ECU code is reprogrammed starting at 0xC000. The program also rewrites the interrupt

table which is at the last block of memory 0xFDFF and above.

Page 41: AutoPlug

40

Figure 5.2.3-1 CAN Bootloader Flow

5.2.4 Hardware Diagrams

The complete system can be rebuilt by putting together the blocks found in the appendix. Please

refer to appendix A2 for all of the diagrams, including the auxiliary circuit diagrams as well as a

diagram of the whole system in figure A2-14. The whole system diagram is meant to be a high

Boot-Loader Starts at 0xF300 Initialize CAN, Disable Interrupts

Check to see if code already written (Flag at 0xEFFE)

Yes

NO Erase Flash Blocks (0xC000 – 0xEF00)

Erase Interrupt Block: (0xFDFF)

Wait for message from Middleware

Is message all 0s? Yes Jump to Program

(JMP 0xC000)

NO

Write to Flash. Bytes 0-1 = Address Bytes 2-7 = Instructions

Send middleware ACK message

Page 42: AutoPlug

41

level description of the system, meaning that the wires do not represent single wires but simply

directions of communication. Refer to the individual blocks for all of the connections.

For brevity, only one controller is discussed here.

Figure 5.2.4 -1 shows the hardware diagram of the differential controller:

5.2.4-1 Differential ECU

The ECUs can get two types of inputs from TORCS, analog or digital. Analog inputs are filtered

using a 10 uF capacitor in order to smooth out the signal. These can be read directly into the A/D

port of the microcontroller. Digital inputs can be read directly into any of the digital ports of the

HCS12.

In order to output back to TORCS, there can be either digital outputs or PWM outputs. Digital

outputs need no conversion, but PWM outputs need to be converted to analog in order to be read

it by the DAQ. The conversion is performed by an RC filter and a voltage follower. The

schematics for these can be found in Appendix A2. Virtually all of our PWM outputs need to be

processed through the RC filter for TORCS to read them.

The actual peripherals we use are simple enough that we could interface them with the ECUs

without much conversion, with the exception of the steering wheel. The pedals were two 100K

Ohm potentiometers that allowed us to read a variable voltage as the individual pedal was

pressed. This is read in by the ECU through an A/D port. The steering wheel is a similar circuit,

but instead of giving out variable voltage, it gave out variable current. This meant that we had to

interface it though a 555 timer in order to read it in to the ECU. The 555 timer outputs a PWM

signal with a variable duty cycle that depends on the time it takes a capacitor attached to the

steering wheel to charge. The way this works is that a reset signal is sent by the ECU every

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 30 – PWM2

Pin 18 – A/D 0

DIFF OUT (RC_IN) TO TORCS

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL 10 uF

YAW_ERR FROM TORCS

Page 43: AutoPlug

42

700Hz, discharging the capacitor. The variable current from the steering wheel then charges the

capacitor and the 555 timer outputs a square wave the displays this time, once the capacitor

discharges, the process starts again. This allows us to read in the steering angle by reading in the

duty cycle of the square wave.

5.3 MIDDLEWARE

5.3.1 Visualizations

In order to verify the operation of the ECU network as well as provide some visual feedback for

the middleware layer, a dashboard was implemented that displayed the vital information of the

vehicle. The data could be visualized through gauges and figures, or it could be displayed in its

raw form. This aided us in debugging our system. Figure 5.3.1-1 shows a screenshot of the data

visualization of the middleware layer. For other screenshots, please refer to appendix A7 for any

additional screenshots.

Figure 5.3.1-1 Visualization

5.3.2 Data Logging

Data logging is an option that can be enabled through the diagnostics pane of the Middleware

GUI. By enabling this feature, the system will begin storing all of CAN data to a file. This data

can later be used to run the same features that middleware provides, such as remote diagnostics

and trip visualizations. This is one of the major features of our system as it gives the vehicle

manufacturers a wealth of information regarding the vehicles on the road. By analyzing historical

data, the manufacturer can alert the user of upcoming tune ups and check-ups, as well as warn

the user then there is a problem with the vehicle before anything major happens.

Page 44: AutoPlug

43

Data logs also have the potential to be used to improve future iterations of vehicles. For example,

if the vehicle manufacturer determines that the tire pressure sensors in the current line of vehicles

seems to fail too often, they can make sure to address this issue in their next model.

5.3.3 ECU Upgrades

This feature consists of being able to upgrade an ECU through the CAN bus without having to

physically access the ECU. The ECU side of ECU upgrades was described in the CAN Boot

loader section (Section 5.2.3). For completeness, the middleware code flow is described here:

Control Flow:

Send jump to boot loader message LEN:2 ID:2 MSG: [ECUID 0x03]

Wait for ACK message: LEN:2 ID:2 MSG:[ECUID 0x01]

Send instruction data from BIN file

Send Finish (Jump to code) message

The middleware reads from a BIN file, which can be extracted from the compiled data that the

Codewarrior IDE creates. Figure 5.3.3-1 shows the middleware upgrading the ECU.

Figure 5.3.3-1 Upgrading ABS ECU

Page 45: AutoPlug

44

5.3.4 Diagnostics

We implemented diagnostic routines for the ECUs to verify their operation. Through the

diagnostics pane, the middleware can run these routines and determine whether an ECU is

working correct and incorrectly.

For example, the diagnostic routine for the cruise control ECU saves the reference speed, and

then compares it to the actual speed. If the actual speed deviates too much from the reference

speed, then the ECU is labeled as working incorrectly. Refer to Figure 5.4.1-2 for an example of

the cruise control diagnostics window.

5.3.5 Android Application

As an additional feature, we also implemented an Android application that shows the data from

the vehicle using similar visualizations as can be found in the dashboard pane of the middleware

layer. The mobile application also has a small demonstration of how it appear if manufacturers

were to push updates to vehicles through user‘s mobile phones. While the upgrade process is

simply for demonstration and does not upgrade any ECU in our system, we thought it would

illustrate our concept well. Please refer to Appendix A7 for additional screenshots of the Android

application.

5.4 OVERALL SYSTEM

In addition to completing the individual goals of implementing each of the three layers of

AutoPlug, we also accomplished the overall goal of being able to develop and demonstrate

applicable scenarios for AutoPlug.

5.4.1 Scenario 1: Broken Cruise Control

In this scenario we intentionally flashed the cruise control ECU with pathological software that

gave undesired operation. This demonstrated the potential for software errors to be diagnosed

and corrected through AutoPlug.

When cruise control was enabled, the vehicle erratically attempted to match the desired speed,

which was seen in simulation and recorded by the middleware layer (Fig. 5.4.1-1).

Page 46: AutoPlug

45

Figure 5.4.1-1 Pathological Cruise Control Operation

We were then able to run diagnostics on the middleware layer in order to quantitatively

recognize the error (Fig 5.4.1-2).

Figure 5.4.1-2 ECU Diagnostic Info

2 3 4 5 6 7 8 9 10

0

25

50

75

100

Time (s)

Ve

hic

le S

pe

ed

(km

/h)

2 3 4 5 6 7 8 9 10

-100

0

100

50

-50

Cru

ise

Co

ntr

ol A

cce

l./B

rake

Co

mm

an

d (

no

rma

lize

d to

+/-

10

0)Pathological Cruise Control Operation

Speed

Cruise Control Command.

Page 47: AutoPlug

46

The user was then able to upgrade the ECU with the correct version of the software. After

flashing the new software, the user was able to verify that the cruise control was working

correctly (previously shown in Fig. 5.2.2.1-1).

5.4.2 Scenario 2: Broken ABS/Brakes

In this scenario we intentionally flashed the ABS/Brakes ECU with pathological software that

gave undesired operation. This demonstrated the ability of AutoPlug to diagnose any node on

the ECU network.

When the user quickly engaged brakes at high speed, the vehicle applied the brakes incorrectly,

causing the wheels to lock and the car to violently spin around, which was seen in simulation and

recorded by the middleware layer (Fig. 5.4.2-1).

Figure 5.4.2-1 Pathological ABS/Brakes Operation

More graphs of pathological ECU operation can be found in Appendix A4.2.

We were then able to run diagnostics on the middleware layer in order to quantitatively

recognize the error, similar to Fig 5.4.1-2. The user then upgraded the ECU with the correct

version of the software. After flashing the new software, the user was able to verify that the

ABS/Brakes ECU was working correctly (previously shown in Fig. 5.2.2.2-1).

0

50

100Pathological ABS/Brakes Operation: Vehicle Vs. Wheel Speed

0

50

100

Sp

ee

d (

km

/h)

0

50

100

2 2.5 3 3.5 4 4.5 50

50

100

Time (s)

Vehicle

Wheel (FR)

Vehicle

Wheel (FL)

Vehicle

Wheel (RR)

Vehicle

Wheel(RL)

Page 48: AutoPlug

47

6. LESSONS LEARNED

It is very important to know the limitations of hardware and software tools that one may use to

complete a project, particularly before any designs are finalized. During our implementation of

the ECU network as well as the simulation, we ran into a few problems that were caused by our

ignorance of the limitations of our devices. The DAQ boards we used only had a set number of

analog inputs, so we were not able to export as many physics outputs from TORCS as we had

hoped. Another instance of this came with the onboard CAN transceivers that we used with our

HCS12 variant. Due to the quality of the transceivers, coupled with the inexpensive components

we were using, the CAN bus that we implemented had a limit of about 10 nodes before the

signals attenuated too much for the nodes to send messages.

When working in an inter-disciplinary team, make sure that interface documents are in a

language that everyone can understand. Describing details that two parties need to be aware of in

vague terms leads to confusion and sometimes leads to perform tasks over again. This is also true

when working with people that have differing work methodology. Interface documents serve to

not only keep different parts of a project consistent with the overall system, but to also allow

different members of the team to work independently without constant collaboration. This lets

every member work at their own pace.

Address the difficult problems early. If a feature is the cornerstone of the whole project (such as

ECU Firmware Upgrades was for ours), it should be approached with enough time implement or

allow for alternative solutions. We waited way too long to address this feature and we were

fortunate to have completed it in time.

Page 49: AutoPlug

48

7. EQUIPMENT NEEDS

Most of the equipment we needed was available from our advisor‘s lab (the mLab) as well as the

Detkin Lab. A few items were purchased from different vendors for a better user experience and

practicality. Please refer to section 12 (Financial Information) for a full list of items.

Page 50: AutoPlug

49

8. CONCLUSIONS AND RECOMMENDATIONS

Overall, we felt the project was successful and that the goals that we met were accomplished

thoroughly. However, removing some of our limitations could have made our project even better.

For example, we wanted the automobile model to be more robust and support more features, but

due to time constraints and limitations of our simulation and hardware, we could not meet this

goal.

We did meet the goals that we set out to complete in our first proposal. If the project were to be

redone, we would not have done it any differently, as we feel our system met the specifications

we set out to meet.

1. We learned how to work in a team of different disciplines and work styles.

2. Vehicle electronics are complex systems. The amount of electronic states increases

drastically for each ECU that is added. This makes ECU design very difficult and hard to

debug.

3. Our system was mostly limited hardware and our simulation. A more extensive and

specific simulator would have allowed us to create more realistic systems, but due to

price constraints, this was not possible.

4. Issues of privacy and security are big problems that need to be addressed for a project

such as this. This is the reason projects like AutoPlug haven‘t come to fruition in a

corporate setting.

5. For the future, the backend that the manufacturers could use to access AutoPlug could be

implemented.

6. Fleet management is a big issue. We were not concerned with how AutoPlug would scale

in a realistic setting. More work could be done in implementing a way for vehicle

manufacturers to deploy AutoPlug to the market.

If this project were to continue, we recommend that the people work working on this project

focus on these areas:

Security/privacy

Real-time systems and control

Higher-fidelity simulation

Page 51: AutoPlug

50

9. NOMENCLATURE

ABS – Anti-lock Braking System

API – Application Programming Interface

BeagleBoard – a small, single board computer

C – Programming Language

CAN – Controller Area Network

DAQ – Data Acquisition

ECU – Electronic Control Unit

ESC – Electronic Stability Control

GUI – Graphical User Interface

MATLAB – Matrix Laboratory; numerical linear algebra computation suite

OBD – On-Board Diagnostics

OEM – Original Equipment Manufacturer

OMAP3- Open Multimedia Platform, a computer architecture for mobile and low powered

devices.

Open Source – A software paradigm that promotes openness and transparency in code.

OSEK – a real-time operating system used in car electronics

PID– Proportional + Integral + Derivative

PWM – Pulse Width Modulation

RTOS – Real-Time Operating System

Simulink – control systems/signal processing simulation and design suite

Ubuntu – Linux distribution

Page 52: AutoPlug

51

10. REFERENCES

[1] (2010, March 2). Ford, GM lead in U.S. auto recalls 2005-2009, p.1. Retrieved from

http://www.reuters.com/article/idUSN0218660120100303

[2] J. Erjavec, Automotive Technology: A Systems Approach. United States: Thompson Delmar

Learning, 2004.

[3] R. Charette. (2010, Feb. 5). This Car Runs on Code. Discovery News, p.1. Retrieved

November 5, 2010, from http://news.discovery.com/tech/toyota-recall-software-code.html

[4] N.V. (2010, May 16). Tech.View: Cars and software bugs. The Economist, p. 1. Retrieved

November 3, 2010, from

http://www.economist.com/blogs/babbage/2010/05/techview_cars_and_software_bugs

[5] W. Voss, A Comprehensible Guide to Controller Area Network. Greenfield, MA: Copperhil

Media, 2005.

[6] (2010, June 8). Chrysler recalls more than half a million vehicles. Newsome Law Firm, p.1.

Retrieved from http://www.newsomelaw.com/blog/2010/06/08/chrysler-recalls-more-half-

million-vehicles

[7] K. Koscher, et al., ―Experimental security analysis of a modern automobile,‖ in Symposium

on Security and Privacy, Oakland, California, 2010.

[8] H. Heinecke, ―Automotive Open System Architecture – An Industry-wide Initiative to

Manage the Complexity of Emerging Automotive E/E-Architectures,‖ Society of Automotive

Engineers World Congress, Detroit, Michigan, 2004.

[9] I.J.M. Besselink, ―Vehicle dynamics analysis using SimMechanics and TNO Delft-Tyre,‖

TNO Automotive - Eindhoven University of Technology, The Netherlands, 2006.

[10] A. R. W. Huang and C. Chen, ―A Low-Cost Driving Simulator for Full Vehicle Dynamics

Simulation.‖ IEEE Transactions on Vechicular Technology, vol. 52, no. 1, January 2003, pp.

162-172.

[11] T. Kinjawadekar, ―Model-based Design of Electronic Stability Control System for

Passenger Cars Using CarSim and Matlab-Simulink,‖ Master‘s Thesis in Mechanical

Engineering at Ohio State University, 2009.

[12] M. Chunyang, S. Lining, D. Zhijiang, and C.Yanchun, ― Research and Development of

Device for Downloading and Updating Software of Product ECU based on Extended CCP,‖

Robot Research Institute, Harbin, China, May 2007.

[13] D. Xue, X. Yin, and L. Li, ―Software Architecture for the ECU of Automated Manual

Page 53: AutoPlug

52

Transmission,‖ College of Mechanical and Automotive Engineering, Hunan University,

Chengdu, China, June 2010.

[14] H. Bischof, B. Donhauser, and K. Meder, ―The ECU of a Rear Wheel Steering System,‖

London, UK, Oct. 1991.

[15] G. Raravi, K. Ramamritham, and N. Sharma, ―Real-time Data Services for Automotive

Applications,‖, Bombay, India, June 2007.

[16] S. Seo, S. Lee, S. Hwang, and J.W. Jeon, ―Analysis of Task Switching Time of ECU

Embedded System Ported to OSEK(RTOS),‖ Suwon, Korea, Oct. 2006.

[17] Corporate Overview. Retrieved from

http://www.freescale.com/webapp/sps/site/overview.jsp?code=CORPORATE_OVERVIEW

Page 54: AutoPlug

53

11. BIBLIOGRAPHY

D. Assanis et al., ―Validation and Use of SIMULINK Integrated, High Fidelity, Engine-In-

Vehicle Siimulation of the International Class VI Truck,‖ Automotive Research Center,

University of Michigan, Tech. Rep. 2000-01-0288, March 2000.

M. Burress, ―Torque vectoring,‖ Lotus International.

BeagleBoard Datasheet. Retrieved from www.beagleboard.org

C. Lin et al., ―Integrated, Feed-Forward Hybrid Electric Vehicle Simulation in SIMULINK and

its Use or Power Management Studies,‖ Automotive Research Center, University of Michigan,

Tech. Rep. 2001-01-1334, January 2001.

MC9S12C128 Datasheet. Retrieved from

http://www.datasheetpro.com/7054_view_MC9S12C128_datasheet.html

MCP2551 Datasheet. Retrieved from

http://ww1.microchip.com/downloads/en/DeviceDoc/21667f.pdf

K. Sawase et.al, ―Development of Central-Differential Control Sytem for High-Performance

Four-Wheel-Drive Vehicles,‖ Mitsubishi Motors Technical Review (2001, no. 13).

G. Smid, K. Cheok and K. Kobayashi, ―Modeling of Vehicle Dynamics using Matrix-Vector

Oriented Calculation in Matlab,‖ in CAINE 1996 ( ISCA, Orlando FL, Dec. 1996, pp 115-120).

B. Wall, ―Development and analysis of a vehicle model in SimMechanics for Formula Student,‖

Eindhoven University of Technology, The Netherlands, Tech Rep. 2005.68, May 2005.

Page 55: AutoPlug

54

12. FINANCIAL INFORMATION

As stated earlier, most components that are necessary for this project are available in the mLab.

We purchased a steering wheel and a set of pedals to improve the usability of our system. We

also purchased some generic printed circuit boards to set up our circuits for demonstration. All of

the HCS12‘s used as ECUs were provided to us by the Detkin Lab and the computers we used

were either personal computers or Professor Mangharam‘s. At the beginning of the project, we

also purchased several CAN transceivers that we did not end up using due to the usability of the

CAN transceivers already available on the HCS12 boards.

Interact V3 Racing Wheel and Pedals – $27

JAMECO PCBs – $24

MCP2551 CAN Transceivers – $28

Total: $79

Page 56: AutoPlug

55

13. ETHICS

The concept behind AutoPlug consisted of aiding vehicle manufacturers in their ability to deal

with recalls as well as unavoidable software errors. AutoPlug is a platform that could be used for

designing automobiles in the future and therefore it inherited most ethical issues of automotive

design. Most of the issues have already been addressed due to the existence and availability of

vehicles today and thus they do not need to be addressed by our system.

13.1 DESCRIPTION OF LARGER CONTEXT

Assuming that AutoPlug is adopted and adapted by the vehicle manufacturers in order to design

new vehicles, the major ethical components that were not addressed by our system design were

that of privacy and security in our system. Because our system was an open architecture and

gave access to the software manufacturer to analyze and alter the internal operation of the

vehicle, certain precautions need to be taken into account to address the problems of abuse of

this data as well as the possibility of unwanted tampering of the vehicle by an intruder.

13.2 ANALYSIS OF ETHICAL ISSUES

A user of AutoPlug would have to be protected against privacy intrusions such as the use of their

automobile data in advertising, personal data mining or even government issues. The user must

be informed of the full extent of what their vehicle data will be used for.

On the same note, the user should be protected against unwanted intrusions by other parties that

are not the vehicle manufacturer. Things such as software viruses and hacking become real

threats when systems such as ours are adopted. A system like AutoPlug opens up the modern car

to dangers that are found in most home computers today, and the final design needs to take these

problems into consideration.

13.3 ETHICAL RECOMMENDATIONS

For the issue of privacy, we envisioned a subscriber model in which the user could themselves

choose to upload data to the manufacturer, and they should be given the ability to classify which

data gets uploaded. Personal information, including vehicle location should only be uploaded to

the manufacturer by user consent.

Security is another problem altogether, and it should be addressed carefully by using accepted

methods of security found in critical systems today. High level encryption algorithms as well as

secure connections should be used between the vehicles out on the road and the car

manufacturers. There should also be security measures built into the ECUs to prevent unwanted

attacks on the control units themselves.

Page 57: AutoPlug

56

14. SOFTWARE DOCUMENTATION

Please refer to Appendix A1 for our revisions of the pedals ECU.

Page 58: AutoPlug

57

15. APPENDICES

A1 CODE FOR SOFTWARE MODULE “PEDALS” ..................................................................................................... 58

A2 HARDWARE DIAGRAMS ................................................................................................................................ 107

A3 CONTROL DIAGRAMS ................................................................................................................................... 116

A4 ADDITIONAL GRAPHS ................................................................................................................................... 119

A4.1 EXAMPLE ABS/BRAKES OPERATION .............................................................................................................. 119 A4.2 PATHOLOGICAL ABS/BRAKES OPERATION .................................................................................................... 121 A4.3 CABIN COMFORT CONTROLLER .................................................................................................................... 124

A5 DATASHEETS ................................................................................................................................................. 125

A6 MATHEMATICAL EQUATIONS ....................................................................................................................... 126

A7 ADDITIONAL SCREENSHOTS .......................................................................................................................... 127

Page 59: AutoPlug

58

A1 CODE FOR SOFTWARE MODULE “PEDALS”

/*

Title: Pedals - Revision 9

Author: Gabriel Torres and Ross Boczar

Date: 4-20-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 4-20-2011

Revision List:

Added an output compare to send CAN messages at a set interval - Gabriel Torres

Different CAN implementation, slowed down messages - Gabriel Torres

Added new CAN functions and bug fixes - Gabriel Torres

Bug Fixes on A/D code - Gabriel Torres

Bug fixes on Cruise Control - Ross Boczar

Added Cruise Control support - Ross Boczar

Added CAN code - Gabriel Torres

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

#include "can.h"

#include "autoplug_types.h"

#define IDENTIFIER 0x04

#define limit(x,a,b) ((x < a) ? (a) : ((x > b) ? (b) : (x)))

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

int control;

int cruiseModeMsg;//receives and sends cruiseMode msg

int TracMsg;//receives tracmsg

signed int cruiseAccelMsg;//receives cruiseAccel msg

PedalMsg pedalMsg;//sends pedalmsg

Page 60: AutoPlug

59

int cruiseEn;//intermediate variable

int oldbrake, oldaccel;

int FIRMWARE;

//must put in a rountine in CAN to update these

void interrupt 38 canrx(void){

short int message[8];

int i =0;

int len = CANRXDLR;

unsigned int id = 0;

id = ((CANRXIDR0) << 3) | ((CANRXIDR1) >> 5); //ID of received message

for (i = 0; i < len; i++){

CANMSG[i]= *(&CANRXDSR0+i);

}

if (id == 0x08){

cruiseModeMsg =CANMSG[0];

}

if (id == 0x09){

cruiseAccelMsg = (signed int)(CANMSG[0] -100);

}

if (id == 0x0F){

TracMsg = CANMSG[0];

}

if (id == 0x02){

if (CANMSG[0] == IDENTIFIER){

if (CANMSG[1] == 0x03){

DisableInterrupts;

CANRFLG |=1;

asm("JMP 0xF300");

} else if (CANMSG[1] == 0x02){

message[0] = IDENTIFIER;

message[1] = (FIRMWARE & 0xFF00) >> 8;

message[2] = (FIRMWARE & 0x00FF);

send_msg(message, 0x02, 3);

}

}

}

Page 61: AutoPlug

60

CANRFLG |= 1; //reset flag

}

void interrupt 13 can_control(){

/* SEND CAN MESSAGES HERE */

if (oldbrake != pedalMsg.brakeCmd){

send_msg(&pedalMsg.brakeCmd, 0x0004, 1);

oldbrake = pedalMsg.brakeCmd;

}

if (oldaccel != pedalMsg.accelCmd){

send_msg(&pedalMsg.accelCmd, 0x0007, 1);

oldaccel = pedalMsg.accelCmd;

}

TC5 = TCNT + 50000;

TFLG1 |= 0x20;

}

void can_control_init(void){

TSCR1 |= 0x80;

TSCR2 = 0x01; //prescale the timer by 2

TFLG1 |=0x20;

TIE |= 0x20;

TIOS |= 0x20;//Enable output compare on TC5

TC5 = TCNT + 50000;

}

Page 62: AutoPlug

61

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

void adc_init(void){

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x10; //1 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

Page 63: AutoPlug

62

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void main( ){

int accel=0;

int brake=0;

cruiseModeMsg=0;//receives and sends cruiseMode msg

cruiseAccelMsg=0;//receives cruiseAccel msg

oldaccel = 0;

oldbrake =0;

TracMsg=0;//traction control

pedalMsg.accelCmd=0;

pedalMsg.brakeCmd=0;//sends pedalmsg

cruiseEn=0;//intermediate variable

//Init Functions

maxval = 1023;

init_CAN(0x0008,0x0009,0x002,0xF); //Accepting cc_mode and cc_accel

pwm_init();

adc_init();

Page 64: AutoPlug

63

can_control_init();

FIRMWARE = 0x0101;

EnableInterrupts;

while(1){

while(!(ATDSTAT0 & 0x80));

//Get Input pedal data

accel = ATDDR0/10;

brake = ATDDR1/10;

//Priority: kill message

if (accel>15 || brake>15){

if (cruiseModeMsg || cruiseEn){//If cruise is on and should be killed

cruiseModeMsg=0; //KILL cruise

cruiseEn=0;

send_msg(&cruiseModeMsg, 0x0008, 1);

}

}

else{ //Else, set as normal

cruiseEn=cruiseModeMsg;

}

if(cruiseEn) { //If cruise is on

if (cruiseAccelMsg>=0){

accel=cruiseAccelMsg;

brake=0;

}

else {

accel=0;

brake=-cruiseAccelMsg;

}

}

//Alwys add traction

//accel=limit(accel-TracMsg, 0, 100);

Page 65: AutoPlug

64

pedalMsg.brakeCmd = brake;

pedalMsg.accelCmd = accel;

set_duty(pedalMsg.accelCmd,pedalMsg.brakeCmd);

ATDSTAT0|=0xF0;

}

}

Page 66: AutoPlug

65

/*

Title: Pedals - Revision 8

Author: Gabriel Torres and Ross Boczar

Date: 4-18-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 4-18-2011

Revision List:

Different CAN implementation, slowed down messages - Gabriel Torres

Added new CAN functions and bug fixes - Gabriel Torres

Bug Fixes on A/D code - Gabriel Torres

Bug fixes on Cruise Control - Ross Boczar

Added Cruise Control support - Ross Boczar

Added CAN code - Gabriel Torres

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

#include "can.h"

#include "autoplug_types.h"

#define IDENTIFIER 0x04

#define limit(x,a,b) ((x < a) ? (a) : ((x > b) ? (b) : (x)))

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

int control;

int cruiseModeMsg;//receives and sends cruiseMode msg

int TracMsg;//receives tracmsg

signed int cruiseAccelMsg;//receives cruiseAccel msg

PedalMsg pedalMsg;//sends pedalmsg

int cruiseEn;//intermediate variable

int FIRMWARE;

Page 67: AutoPlug

66

//must put in a rountine in CAN to update these

void interrupt 38 canrx(void){

short int message[8];

int i =0;

int len = CANRXDLR;

unsigned int id = 0;

id = ((CANRXIDR0) << 3) | ((CANRXIDR1) >> 5); //ID of received message

for (i = 0; i < len; i++){

CANMSG[i]= *(&CANRXDSR0+i);

}

if (id == 0x08){

cruiseModeMsg =CANMSG[0];

}

if (id == 0x09){

cruiseAccelMsg = (signed int)(CANMSG[0] -100);

}

if (id == 0x0F){

TracMsg = CANMSG[0];

}

if (id == 0x02){

if (CANMSG[0] == IDENTIFIER){

if (CANMSG[1] == 0x03){

DisableInterrupts;

CANRFLG |=1;

asm("JMP 0xF300");

} else if (CANMSG[1] == 0x02){

message[0] = IDENTIFIER;

message[1] = (FIRMWARE & 0xFF00) >> 8;

message[2] = (FIRMWARE & 0x00FF);

send_msg(message, 0x02, 3);

}

}

}

CANRFLG |= 1; //reset flag

}

Page 68: AutoPlug

67

void interrupt 8 OC(){

TFLG1 = 0x01;

TC0 = TCNT + 10000;

control = 1;

}

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

void adc_init(void){

int wait1=10000;

Page 69: AutoPlug

68

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x10; //1 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void timer_init(void){

TSCR1 = 0x80; //Enable Timer

TSCR2 = 0x01; //Prescale clock by 2;

TIOS = 0x01;

TIE = 0x01;

TFLG1 = 0x01;

TC0 = TCNT + 50000;

Page 70: AutoPlug

69

}

void main( ){

int accel=0;

int brake=0;

cruiseModeMsg=0;//receives and sends cruiseMode msg

cruiseAccelMsg=0;//receives cruiseAccel msg

TracMsg=0;//traction control

pedalMsg.accelCmd=0;

pedalMsg.brakeCmd=0;//sends pedalmsg

cruiseEn=0;//intermediate variable

//Init Functions

maxval = 1023;

init_CAN(0x0008,0x0009,0x002,0xF); //Accepting cc_mode and cc_accel

pwm_init();

adc_init();

timer_init();

control = 0;

FIRMWARE = 0x0101;

EnableInterrupts;

while(1){

while(!control){};

control = 0;

while(!(ATDSTAT0 & 0x80));

//Get Input pedal data

accel = ATDDR0/10;

brake = ATDDR1/10;

//Priority: kill message

if (accel>15 || brake>15){

if (cruiseModeMsg || cruiseEn){//If cruise is on and should be killed

cruiseModeMsg=0; //KILL cruise

cruiseEn=0;

send_msg(&cruiseModeMsg, 0x0008, 1);

}

Page 71: AutoPlug

70

}

else{ //Else, set as normal

cruiseEn=cruiseModeMsg;

}

if(cruiseEn) { //If cruise is on

if (cruiseAccelMsg>=0){

accel=cruiseAccelMsg;

brake=0;

}

else {

accel=0;

brake=-cruiseAccelMsg;

}

}

//Alwys add traction

//accel=limit(accel-TracMsg, 0, 100);

if (pedalMsg.accelCmd != accel || pedalMsg.brakeCmd != brake){

set_duty(accel,brake);

if (pedalMsg.accelCmd != accel) {

send_msg(&accel, 0x0007, 1);

}

if (pedalMsg.brakeCmd != brake){

send_msg(&brake, 0x0004, 1);

}

pedalMsg.brakeCmd = brake;

pedalMsg.accelCmd = accel;

}

ATDSTAT0|=0xF0;

}

}

Page 72: AutoPlug

71

/*

Title: Pedals - Revision 7

Author: Gabriel Torres and Ross Boczar

Date: 4-10-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 4-10-2011

Revision List:

Added new CAN functions and bug fixes - Gabriel Torres

Bug Fixes on A/D code - Gabriel Torres

Bug fixes on Cruise Control - Ross Boczar

Added Cruise Control support - Ross Boczar

Added CAN code - Gabriel Torres

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

#include "autoplug_types.h"

#define limit(x,a,b) ((x < a) ? (a) : ((x > b) ? (b) : (x)))

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

int cruiseModeMsg=0;//receives and sends cruiseMode msg

signed int cruiseAccelMsg=0;//receives cruiseAccel msg

PedalMsg pedalMsg={0,0};//sends pedalmsg

//must put in a rountine in CAN to update these

void interrupt 38 canrx(void){

unsigned int received = 0;

unsigned long id = 0;

id = ((CANRXIDR0) << 3) | ((CANRXIDR1) >> 5); //ID of received message

Page 73: AutoPlug

72

received = CANRXDSR0; //Received message, only one byte at the moment.

if (id == 0x08){

cruiseModeMsg = received;

}

if (id == 0x09){

cruiseAccelMsg = (signed int)(received -100);

}

CANRFLG |= 1; //reset flag

}

int cruiseEn=0;//intermediate variable

//init_CAN function, specify 4 IDs to accept, if less than 4, replace with 0.

void init_CAN(long int id1, long int id2, long int id3, long int id4){

CANCTL1_CANE = 1; // Enable CAN module

CANCTL0_INITRQ = 1; // Request initialization mode

while(!CANCTL1_INITAK) ; // Wait until initialization mode is entered

CANCTL1 = 0x80; // Enable CAN, OSCCLK as CAN clock

CANBTR0 = 0xC0; // SJW = 4, Prescaler = 4

CANBTR1 = 0x23; // Tseg1 = 4, Tseg2 = 3 can rate: 500kbits

CANIDAC = 0x10; // 16-bit filter mode 4 acceptance IDs

//Filter 1

CANIDAR0 = (id1 & 0xFFF8) >> 3;

CANIDAR1 = (id1 & 0x0007) << 5;

//Filter 2

CANIDAR2 = (id2 & 0xFFF8) >> 3;

CANIDAR3 = (id2 & 0x0007) << 5;

//Filter 3

CANIDAR4 = (id3 & 0xFFF8) >> 3;

CANIDAR5 = (id3 & 0x0007) << 5;

//Filter 4

CANIDAR6 = (id4 & 0xFFF8) >> 3;

CANIDAR7 = (id4 & 0x0007) << 5;

Page 74: AutoPlug

73

CANIDMR0 = 0x00; // Set all bits to care

CANIDMR1 = 0x00;

CANIDMR2 = 0x00;

CANIDMR3 = 0x00;

CANIDMR4 = 0x00;

CANIDMR5 = 0x00;

CANIDMR6 = 0x00;

CANIDMR7 = 0x00;

//CANCTL1_LOOPB = 1; // Enable loopback (ONLY FOR TESTING)

CANCTL0_INITRQ = 0; // Exit initialization mode

while(CANCTL1_INITAK) ;

CANRIER |= 1; //enable CAN interrupt

}

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

Page 75: AutoPlug

74

void adc_init(void){

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x10; //2 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

void send_msg(int msg, long int id){

unsigned char nextcan;

nextcan = CANTFLG;

CANTBSEL = nextcan;

CANTXIDR0 = (id & 0xFFF8) >> 3;

CANTXIDR1 = (id & 0x0007) << 5;

CANTXIDR2 = 0x00;

CANTXIDR3 = 0x00;

CANTXDSR0 = msg;

CANTXDLR = 0x01;

CANTFLG = CANTBSEL;

while( (CANTFLG & nextcan) != nextcan);

}

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

Page 76: AutoPlug

75

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void main( ){

int accel=0;

int brake=0;

//Init Functions

maxval = 1023;

//init_CAN(0x0008,0x0009,0,0); //Accepting cc_mode and cc_accel

pwm_init();

adc_init();

DDRA=0xFF;

EnableInterrupts;

while(1){

while(!(ATDSTAT0 & 0x80));

//Get Input pedal data

accel = ATDDR0/10;

brake = ATDDR1/10;

//Priority: kill message

if (accel>15 || brake>15){

if (cruiseModeMsg || cruiseEn){//If cruise is on and should be killed

cruiseModeMsg=0; //KILL cruise

cruiseEn=0;

send_msg(cruiseModeMsg, 0x0008);

Page 77: AutoPlug

76

}

}

else{ //Else, set as normal

cruiseEn=cruiseModeMsg;

}

if(cruiseEn) { //If cruise is on

if (cruiseAccelMsg>=0){

accel=cruiseAccelMsg;

brake=0;

}

else {

accel=0;

brake=-cruiseAccelMsg;

}

}

if (pedalMsg.accelCmd != accel || pedalMsg.brakeCmd != brake){

set_duty(accel,brake);

send_msg(accel, 0x0007);

send_msg(brake, 0x0004);

pedalMsg.brakeCmd = brake;

pedalMsg.accelCmd = accel;

}

ATDSTAT0|=0xF0;

}

}

Page 78: AutoPlug

77

/*

Title: Pedals - Revision 6

Author: Gabriel Torres and Ross Boczar

Date: 3-30-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 3-30-2011

Revision List:

Bug Fixes on A/D code - Gabriel Torres

Bug fixes on Cruise Control - Ross Boczar

Added Cruise Control support - Ross Boczar

Added CAN code - Gabriel Torres

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

#include "autoplug_types.h"

#define limit(x,a,b) ((x < a) ? (a) : ((x > b) ? (b) : (x)))

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

int cruiseModeMsg=0;//receives and sends cruiseMode msg

signed int cruiseAccelMsg=0;//receives cruiseAccel msg

PedalMsg pedalMsg={0,0};//sends pedalmsg

//must put in a rountine in CAN to update these

void interrupt 38 canrx(void){

unsigned int received = 0;

unsigned long id = 0;

id = ((CANRXIDR0) << 3) | ((CANRXIDR1) >> 5); //ID of received message

received = CANRXDSR0; //Received message, only one byte at the moment.

Page 79: AutoPlug

78

if (id == 0x08){

cruiseModeMsg = received;

}

if (id == 0x09){

cruiseAccelMsg = (signed int)(received -100);

}

CANRFLG |= 1; //reset flag

}

int cruiseEn=0;//intermediate variable

//init_CAN function, specify 4 IDs to accept, if less than 4, replace with 0.

void init_CAN(long int id1, long int id2, long int id3, long int id4){

CANCTL1_CANE = 1; // Enable CAN module

CANCTL0_INITRQ = 1; // Request initialization mode

while(!CANCTL1_INITAK) ; // Wait until initialization mode is entered

CANCTL1 = 0x80; // Enable CAN, OSCCLK as CAN clock

CANBTR0 = 0xC0; // SJW = 4, Prescaler = 4

CANBTR1 = 0x23; // Tseg1 = 4, Tseg2 = 3 can rate: 500kbits

CANIDAC = 0x10; // 16-bit filter mode 4 acceptance IDs

//Filter 1

CANIDAR0 = (id1 & 0xFFF8) >> 3;

CANIDAR1 = (id1 & 0x0007) << 5;

//Filter 2

CANIDAR2 = (id2 & 0xFFF8) >> 3;

CANIDAR3 = (id2 & 0x0007) << 5;

//Filter 3

CANIDAR4 = (id3 & 0xFFF8) >> 3;

CANIDAR5 = (id3 & 0x0007) << 5;

//Filter 4

CANIDAR6 = (id4 & 0xFFF8) >> 3;

CANIDAR7 = (id4 & 0x0007) << 5;

Page 80: AutoPlug

79

CANIDMR0 = 0x00; // Set all bits to care

CANIDMR1 = 0x00;

CANIDMR2 = 0x00;

CANIDMR3 = 0x00;

CANIDMR4 = 0x00;

CANIDMR5 = 0x00;

CANIDMR6 = 0x00;

CANIDMR7 = 0x00;

//CANCTL1_LOOPB = 1; // Enable loopback (ONLY FOR TESTING)

CANCTL0_INITRQ = 0; // Exit initialization mode

while(CANCTL1_INITAK) ;

CANRIER |= 1; //enable CAN interrupt

}

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

Page 81: AutoPlug

80

void adc_init(void){

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x20; //2 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

void send_msg(int msg, long int id){

unsigned char nextcan;

nextcan = CANTFLG;

CANTBSEL = nextcan;

CANTXIDR0 = (id & 0xFFF8) >> 3;

CANTXIDR1 = (id & 0x0007) << 5;

CANTXIDR2 = 0x00;

CANTXIDR3 = 0x00;

CANTXDSR0 = msg;

CANTXDLR = 0x01;

CANTFLG = CANTBSEL;

while( (CANTFLG & nextcan) != nextcan);

}

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

Page 82: AutoPlug

81

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void main( ){

int accel=0;

int brake=0;

//Init Functions

maxval = 1023;

init_CAN(0x0008,0x0009,0,0); //Accepting cc_mode and cc_accel

pwm_init();

adc_init();

EnableInterrupts;

while(1){

while(!(ATDSTAT0 & 0x80));

//Get Input pedal data

accel = ATDDR0/10;

brake = ATDDR1/10;

//Priority: kill message

if (accel>15 || brake>15){

if (cruiseModeMsg || cruiseEn){//If cruise is on and should be killed

cruiseModeMsg=0; //KILL cruise

cruiseEn=0;

send_msg(cruiseModeMsg, 0x0008);

}

Page 83: AutoPlug

82

}

else{ //Else, set as normal

cruiseEn=cruiseModeMsg;

}

if(cruiseEn) { //If cruise is on

if (cruiseAccelMsg>=0){

accel=cruiseAccelMsg;

brake=0;

}

else {

accel=0;

brake=-cruiseAccelMsg;

}

}

if (pedalMsg.accelCmd != accel || pedalMsg.brakeCmd != brake){

set_duty(accel,brake);

send_msg(accel, 0x0007);

send_msg(brake, 0x0004);

pedalMsg.brakeCmd = brake;

pedalMsg.accelCmd = accel;

}

ATDSTAT0|=0xF0;

}

}

Page 84: AutoPlug

83

/*

Title: Pedals - Revision 5

Author: Gabriel Torres and Ross Boczar

Date: 3-15-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 3-15-2011

Revision List:

Bug fixes on Cruise Control - Ross Boczar

Added Cruise Control support - Ross Boczar

Added CAN code - Gabriel Torres

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

#include "autoplug_types.h"

#define limit(x,a,b) ((x < a) ? (a) : ((x > b) ? (b) : (x)))

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

int cruiseModeMsg=0;//receives and sends cruiseMode msg

signed int cruiseAccelMsg=0;//receives cruiseAccel msg

PedalMsg pedalMsg={0,0};//sends pedalmsg

//must put in a rountine in CAN to update these

void interrupt 38 canrx(void){

unsigned int received = 0;

unsigned long id = 0;

id = ((CANRXIDR0) << 3) | ((CANRXIDR1) >> 5); //ID of received message

received = CANRXDSR0; //Received message, only one byte at the moment.

Page 85: AutoPlug

84

if (id == 0x08){

cruiseModeMsg = received;

}

if (id == 0x09){

cruiseAccelMsg = (signed int)(received -100);

}

CANRFLG |= 1; //reset flag

}

int cruiseEn=0;//intermediate variable

//init_CAN function, specify 4 IDs to accept, if less than 4, replace with 0.

void init_CAN(long int id1, long int id2, long int id3, long int id4){

CANCTL1_CANE = 1; // Enable CAN module

CANCTL0_INITRQ = 1; // Request initialization mode

while(!CANCTL1_INITAK) ; // Wait until initialization mode is entered

CANCTL1 = 0x80; // Enable CAN, OSCCLK as CAN clock

CANBTR0 = 0xC0; // SJW = 4, Prescaler = 4

CANBTR1 = 0x23; // Tseg1 = 4, Tseg2 = 3 can rate: 500kbits

CANIDAC = 0x10; // 16-bit filter mode 4 acceptance IDs

//Filter 1

CANIDAR0 = (id1 & 0xFFF8) >> 3;

CANIDAR1 = (id1 & 0x0007) << 5;

//Filter 2

CANIDAR2 = (id2 & 0xFFF8) >> 3;

CANIDAR3 = (id2 & 0x0007) << 5;

//Filter 3

CANIDAR4 = (id3 & 0xFFF8) >> 3;

CANIDAR5 = (id3 & 0x0007) << 5;

//Filter 4

CANIDAR6 = (id4 & 0xFFF8) >> 3;

CANIDAR7 = (id4 & 0x0007) << 5;

CANIDMR0 = 0x00; // Set all bits to care

Page 86: AutoPlug

85

CANIDMR1 = 0x00;

CANIDMR2 = 0x00;

CANIDMR3 = 0x00;

CANIDMR4 = 0x00;

CANIDMR5 = 0x00;

CANIDMR6 = 0x00;

CANIDMR7 = 0x00;

//CANCTL1_LOOPB = 1; // Enable loopback (ONLY FOR TESTING)

CANCTL0_INITRQ = 0; // Exit initialization mode

while(CANCTL1_INITAK) ;

CANRIER |= 1; //enable CAN interrupt

}

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

void adc_init(void){

Page 87: AutoPlug

86

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x10; //1 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

void send_msg(int msg, long int id){

unsigned char nextcan;

nextcan = CANTFLG;

CANTBSEL = nextcan;

CANTXIDR0 = (id & 0xFFF8) >> 3;

CANTXIDR1 = (id & 0x0007) << 5;

CANTXIDR2 = 0x00;

CANTXIDR3 = 0x00;

CANTXDSR0 = msg;

CANTXDLR = 0x01;

CANTFLG = CANTBSEL;

while( (CANTFLG & nextcan) != nextcan);

}

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

Page 88: AutoPlug

87

PWMDTY3 = a_temp & 0x00FF;

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void main( ){

int accel=0;

int brake=0;

//Init Functions

maxval = 1023;

init_CAN(0x0008,0x0009,0,0); //Accepting cc_mode and cc_accel

pwm_init();

adc_init();

EnableInterrupts;

while(1){

while(!(ATDSTAT0 & 0x80));

//Get Input pedal data

accel = ATDDR0/10;

brake = ATDDR1/10;

//Priority: kill message

if (accel>15 || brake>15){

if (cruiseModeMsg || cruiseEn){//If cruise is on and should be killed

cruiseModeMsg=0; //KILL cruise

cruiseEn=0;

send_msg(cruiseModeMsg, 0x0008);

}

}

Page 89: AutoPlug

88

else{ //Else, set as normal

cruiseEn=cruiseModeMsg;

}

if(cruiseEn) { //If cruise is on

if (cruiseAccelMsg>=0){

accel=cruiseAccelMsg;

brake=0;

}

else {

accel=0;

brake=-cruiseAccelMsg;

}

}

if (pedalMsg.accelCmd != accel || pedalMsg.brakeCmd != brake){

set_duty(accel,brake);

send_msg(accel, 0x0007);

send_msg(brake, 0x0004);

pedalMsg.brakeCmd = brake;

pedalMsg.accelCmd = accel;

}

ATDSTAT0|=0xF0;

}

}

Page 90: AutoPlug

89

/*

Title: Pedals - Revision 4

Author: Gabriel Torres and Ross Boczar

Date: 2-16-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 2-16-2011

Revision List:

Added Cruise Control support - Ross Boczar

Added CAN code - Gabriel Torres

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

#include "autoplug_types.h"

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

int cruiseModeMsg=0;//receives and sends cruiseMode msg

signed int cruiseAccelMsg=0;//receives cruiseAccel msg

PedalMsg pedalMsg={0,0};//sends pedalmsg

//must put in a rountine in CAN to update these

void interrupt 38 canrx(void){

unsigned int received = 0;

unsigned long id = 0;

id = ((CANRXIDR0) << 3) | ((CANRXIDR1) >> 5); //ID of received message

received = CANRXDSR0; //Received message, only one byte at the moment.

if (id == 0x08){

cruiseModeMsg = received;

Page 91: AutoPlug

90

}

if (id == 0x09){

cruiseAccelMsg = (signed int)(received -100);

}

CANRFLG |= 1; //reset flag

}

int cruiseEn=0;//intermediate variable

//init_CAN function, specify 4 IDs to accept, if less than 4, replace with 0.

void init_CAN(long int id1, long int id2, long int id3, long int id4){

CANCTL1_CANE = 1; // Enable CAN module

CANCTL0_INITRQ = 1; // Request initialization mode

while(!CANCTL1_INITAK) ; // Wait until initialization mode is entered

CANCTL1 = 0x80; // Enable CAN, OSCCLK as CAN clock

CANBTR0 = 0xC0; // SJW = 4, Prescaler = 4

CANBTR1 = 0x23; // Tseg1 = 4, Tseg2 = 3 can rate: 500kbits

CANIDAC = 0x10; // 16-bit filter mode 4 acceptance IDs

//Filter 1

CANIDAR0 = (id1 & 0xFFF8) >> 3;

CANIDAR1 = (id1 & 0x0007) << 5;

//Filter 2

CANIDAR2 = (id2 & 0xFFF8) >> 3;

CANIDAR3 = (id2 & 0x0007) << 5;

//Filter 3

CANIDAR4 = (id3 & 0xFFF8) >> 3;

CANIDAR5 = (id3 & 0x0007) << 5;

//Filter 4

CANIDAR6 = (id4 & 0xFFF8) >> 3;

CANIDAR7 = (id4 & 0x0007) << 5;

CANIDMR0 = 0x00; // Set all bits to care

CANIDMR1 = 0x00;

CANIDMR2 = 0x00;

CANIDMR3 = 0x00;

Page 92: AutoPlug

91

CANIDMR4 = 0x00;

CANIDMR5 = 0x00;

CANIDMR6 = 0x00;

CANIDMR7 = 0x00;

//CANCTL1_LOOPB = 1; // Enable loopback (ONLY FOR TESTING)

CANCTL0_INITRQ = 0; // Exit initialization mode

while(CANCTL1_INITAK) ;

CANRIER |= 1; //enable CAN interrupt

}

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

void adc_init(void){

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

Page 93: AutoPlug

92

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x10; //1 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

void send_msg(int msg, long int id){

unsigned char nextcan;

nextcan = CANTFLG;

CANTBSEL = nextcan;

CANTXIDR0 = (id & 0xFFF8) >> 3;

CANTXIDR1 = (id & 0x0007) << 5;

CANTXIDR2 = 0x00;

CANTXIDR3 = 0x00;

CANTXDSR0 = msg;

CANTXDLR = 0x01;

CANTFLG = CANTBSEL;

while( (CANTFLG & nextcan) != nextcan);

}

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

Page 94: AutoPlug

93

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void main( ){

int accel=0;

int brake=0;

//Init Functions

maxval = 1023;

init_CAN(0x0008,0x0009,0,0); //Accepting cc_mode and cc_accel

pwm_init();

adc_init();

EnableInterrupts;

while(1){

while(!(ATDSTAT0 & 0x80));

//Get Input pedal data

accel = ATDDR0/10;

brake = ATDDR1/10;

//Priority: kill message

if (accel>15 || brake>15){

if (cruiseModeMsg || cruiseEn){//If cruise is on and should be killed

cruiseModeMsg=0; //KILL cruise

cruiseEn=0;

send_msg(cruiseModeMsg, 0x0008);

}

}

else{ //Else, set as normal

cruiseEn=cruiseModeMsg;

}

Page 95: AutoPlug

94

if(cruiseEn) { //If cruise is on

if (cruiseAccelMsg>=0){

accel=cruiseAccelMsg;

brake=0;

}

else {

accel=0;

brake=-cruiseAccelMsg;

}

}

if (pedalMsg.accelCmd != accel || pedalMsg.brakeCmd != brake){

set_duty(accel,brake);

send_msg(accel, 0x0007);

send_msg(brake, 0x0004);

pedalMsg.brakeCmd = brake;

pedalMsg.accelCmd = accel;

}

ATDSTAT0|=0xF0;

}

}

/*

Title: Pedals - Revision 3

Author: Gabriel Torres and Ross Boczar

Date: 1-30-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 1-30-2011

Revision List:

Added CAN code - Gabriel Torres

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

Page 96: AutoPlug

95

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

unsigned long int carspeed;

int accel;

int oldaccel;

int oldbrake;

int controlOutput;

int error;

int errInteg;

int brake;

int carSpeed=0;

int cc_set=0; //0 for pedal, 1 for CAN via cc

int cc_acc=0; //cruise control acc

int cc_kill=0; //kill cruise control

void init_CAN(void){

CANCTL1_CANE = 1; // Enable CAN module

CANCTL0_INITRQ = 1; // Request initialization mode

while(!CANCTL1_INITAK) ; // Wait until initialization mode is entered

CANCTL1 = 0x80; // Enable CAN, OSCCLK as CAN clock

CANBTR0 = 0xC0; // SJW = 4, Prescaler = 4

CANBTR1 = 0x23; // Tseg1 = 4, Tseg2 = 3 can rate: 500kbits

CANIDAC = 0x10; // 16-bit filter mode

CANIDMR0 = 0xFF; // All bits "don't care" (accept all messages)

CANIDMR1 = 0xFF;

CANIDMR2 = 0xFF;

CANIDMR3 = 0xFF;

CANIDMR4 = 0xFF;

CANIDMR5 = 0xFF;

CANIDMR6 = 0xFF;

CANIDMR7 = 0xFF;

//CANCTL1_LOOPB = 1; // Enable loopback (ONLY FOR TESTING)

Page 97: AutoPlug

96

CANCTL0_INITRQ = 0; // Exit initialization mode

while(CANCTL1_INITAK) ;

}

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

void adc_init(void){

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x10; //1 conversions

ATDCTL4=0x00;

Page 98: AutoPlug

97

ATDCTL5=0xB0;

}

void send_msg(int msg, long int id){

unsigned char nextcan;

nextcan = CANTFLG;

CANTBSEL = nextcan;

CANTXIDR0 = (id & 0xFFF8) >> 3;

CANTXIDR1 = (id & 0x0007) << 5;

CANTXIDR2 = 0x00;

CANTXIDR3 = 0x00;

CANTXDSR0 = msg;

CANTXDLR = 0x01;

CANTFLG = CANTBSEL;

while( (CANTFLG & nextcan) != nextcan);

}

/*

int receive_msg(long int *identifier, int *buffer) //CAN RECEIVE FUNCTION

{

unsigned int i;

unsigned int length;

unsigned int *rxPtr;

if(!CANRFLG_RXF) // If data received

return -1;

*identifier = (CANRXIDR0 << 3) + (CANRXIDR1 >> 5);

length = CANRXDLR & 0x0F;

rxPtr = &CANRXDSR0;

for(i = 0; i < length; i++)

{

buffer[i] = *rxPtr;

rxPtr++;

Page 99: AutoPlug

98

}

CANRFLG_RXF = 1; // Reset the flag

return length;

}

*/

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void main( ){

maxval = 1023;

init_CAN();

pwm_init();

adc_init();

DDRA= 0xFF;

oldaccel = 10;

oldbrake = 10;

EnableInterrupts;

while(1){

Page 100: AutoPlug

99

while(!(ATDSTAT0 & 0x80));

//Input pedal data

accel=ATDDR0/10;

brake = ATDDR1/10;

if (oldaccel != accel || oldbrake != brake){

set_duty(accel,brake);

send_msg(accel, 0x0007);

send_msg(brake, 0x0004);

oldbrake = brake;

oldaccel = accel;

}

ATDSTAT0|=0xF0;

}

}

Page 101: AutoPlug

100

/*

Title: Pedals - Revision 2

Author: Gabriel Torres and Ross Boczar

Date: 1-17-2011

Description: Generate a PWM signal based on a potentiometer input from pedals

Backed Up to Dropbox, 1-17-2011

Revision List:

Added Brake - Gabriel Torres

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

unsigned long int data;

unsigned long int carspeed;

int accel;

int oldaccel;

int oldbrake;

int controlOutput;

int error;

int errInteg;

int brake;

int carSpeed=0;

void pwm_init(void){

Page 102: AutoPlug

101

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

PWMDTY4=(brk_duty & 0xFF00)>>8;

PWMDTY5=brk_duty & 0x00FF;

PWMPER4=(period & 0xFF00)>>8;

PWMPER5=period & 0x00FF;

PWME=0xFF;

}

void adc_init(void){

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

ATDCTL3=0x10; //1 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

//takes 1-100

void set_duty(unsigned int a_dty, unsigned int b_dty){

Page 103: AutoPlug

102

unsigned long int a_temp = period;

unsigned long int b_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

//Output range

b_dty=b_dty*80/100+10;

b_temp = b_dty*(period/10)/10;

PWMDTY4 = (b_temp & 0xFF00) >>8;

PWMDTY5 = b_temp & 0x00FF;

}

void main( ){

maxval = 1023;

init_CAN();

pwm_init();

adc_init();

DDRA= 0xFF;

oldaccel = 10;

oldbrake = 10;

EnableInterrupts;

while(1){

while(!(ATDSTAT0 & 0x80));

//Input pedal data

accel=ATDDR0/10;

brake = ATDDR1/10;

Page 104: AutoPlug

103

if (oldaccel != accel || oldbrake != brake){

set_duty(accel,brake);

oldbrake = brake;

oldaccel = accel;

}

ATDSTAT0|=0xF0;

}

}

/*

Title: Pedals - Revision 1

Author: Gabriel Torres and Ross Boczar

Date: 12-17-2010

Description: Generate a PWM signal based on a potentiometer input

Backed Up to Dropbox, 12-17-2010

Revision List:

Initial Implementation - Gabriel Torres

*/

#include <hidef.h> /* common defines and macros */

#include <MC9S12C128.h> /* derivative information */

#pragma LINK_INFO DERIVATIVE "mc9s12c128"

unsigned int period;

unsigned int acc_duty;

unsigned int brk_duty;

unsigned int maxval;

Page 105: AutoPlug

104

unsigned long int data;

unsigned long int carspeed;

int accel;

int oldaccel;

int oldbrake;

int controlOutput;

int error;

int errInteg;

int brake;

int carSpeed=0;

void pwm_init(void){

TSCR1=0x80;//enable timer

DDRP=0xFF; //output pwm

PWMCTL=0x60; //concatenate channels 2&3, 4&5

PWMPRCLK=0x00;//prescale by 64

PWMCLK=0x00;//use clock A/B

PWMPOL=0xFF;// polarity

PWMCAE=0xFF;//align

period=1000; //1 khz

acc_duty=50; //5%

brk_duty=50; //5%

//Set initial pwm and period

PWMDTY2=(acc_duty & 0xFF00)>>8;

PWMDTY3=acc_duty & 0x00FF;

PWMPER2=(period & 0xFF00)>>8;

PWMPER3=period & 0x00FF;

}

void adc_init(void){

int wait1=10000;

int wait2=1000;

ATDCTL2=0x80;

while(wait1--){

while(wait2--);

wait2=10;

}

Page 106: AutoPlug

105

ATDCTL3=0x10; //1 conversions

ATDCTL4=0x00;

ATDCTL5=0xB0;

}

//takes 1-100

void set_duty(unsigned int a_dty){

unsigned long int a_temp = period;

//Output range

a_dty=a_dty*80/100+10;

a_temp = a_dty*(period/10)/10;

PWMDTY2 = (a_temp & 0xFF00) >>8;

PWMDTY3 = a_temp & 0x00FF;

}

void main( ){

maxval = 1023;

pwm_init();

adc_init();

DDRA= 0xFF;

oldaccel = 10;

EnableInterrupts;

while(1){

while(!(ATDSTAT0 & 0x80));

Page 107: AutoPlug

106

//Input pedal data

accel=ATDDR0/10;

if (oldaccel != accel){

set_duty(accel);

oldaccel = accel;

}

ATDSTAT0|=0xF0;

}

}

Page 108: AutoPlug

107

A2 HARDWARE DIAGRAMS

Figure A2-1 STEERING ECU

Figure A2-2 CRUISE CONTROL ECU

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 52 – PT3

Pin 54 – PT4

Pin 36 – PWM5

Pin 50 – PT2

Pin 30 – PWM2

Pin 13 – PT0

Pin 15 – PT1

555 TMR OUT

SHIFT_UP (BTN3)

SHIFT_DN (BTN4)

STEERING OUT (RC_IN) TO TORCS

CC_OFF (BTN2)

555 TMR RESET

CC_ON (BTN1)

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 18 – A/D0 SPEED FROM TORCS

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL CAN_L RAIL

10 uF

Page 109: AutoPlug

108

Figure A2-3 DIFFERENTIAL CONTROL ECU

Figure A2-4 PEDALS ECU

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 30 – PWM2

Pin 18 – A/D 0

DIFF OUT (RC_IN) TO TORCS

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL CAN_L RAIL

10 uF

YAW_ERR FROM TORCS

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 32 – PWM3

Pin 18 – A/D 0

Pin 20 – A/D 1

ACC_OUT (FROM PEDALS)

ACC TO TORCS

BRK_OUT (FROM PEDALS)

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL 10 uF

10 uF

Page 110: AutoPlug

109

Figure A2-5 CABIN COMFORT ECU

Figure A2-5 ENGINE ECU

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 30 – PWM2

Pin 18 – A/D 0

Pin 20 – A/D 1

TEMP FROM TORCS

TEMP_REF FROM POT

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL 10 uF

10 uF

FAN_OUT (RC_IN) TO TORCS

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 47 – PB4

Pin 45 – PB5

Pin 18 – A/D 0

Pin 43 – PB6

RPM FROM TORCS

FUEL_5 FROM TORCS

FUEL_4 FROM TORCS

FUEL_6 FROM TORCS

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL

Pin 53 – PB1

Pin 51 – PB2

Pin 49 – PB3

FUEL_1 FROM TORCS

FUEL_3 FROM TORCS

Pin 55 – PB0 FUEL_0 FROM TORCS

10 uF

FUEL_2 FROM TORCS

Page 111: AutoPlug

110

Figure A2-7 ABS ECU

Figure A2-8 TRANSMISSION ECU

5V

Pin 1 – Vaux

Pin 3 – GND

Pin 24 – A/D 3

Pin 22 – A/D 2

Pin 18 – A/D 0

Pin 20 – A/D 1

WHEEL_1 FROM TORCS

WHEEL_3 FROM TORCS

WHEEL_4 FROM TORCS

WHEEL_2 FROM TORCS

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL

Pin 30 – PP2

Pin 11 – PP1

Pin 9 – PP0

BRAKE_3 (RC_IN) TO TORCS

BRAKE_1 (RC_IN) TO TORCS

Pin 32 – PP3 BRAKE_4 (RC_IN) TO TORCS

10 uF

BRAKE_2 (RC_IN) TO TORCS

10 uF

10 uF

10 uF

5V

Pin 1 – Vaux

Pin 3 – GND

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL

Pin 55 – PB0

Pin 51 – PB2

Pin 53 – PB1

Pin 49 – PB3

Pin 45 – PB5

Pin 47 – PB4

GEAR_2 FROM TORCS

GEAR_0 TO TORCS

GEAR_2 TO TORCS

GEAR_1 TO TORCS

GEAR_0 FROM TORCS

GEAR_1 FROM TORCS

Page 112: AutoPlug

111

Figure A2-9 CONSOLE ECU

5V

Pin 1 – Vaux

Pin 3 – GND

HCS12

CAN HIGH

CAN LOW

CAN_H RAIL

CAN_L RAIL

Pin 55 – PB0

Pin 51 – PB2

Pin 53 – PB1

Pin 39 – PA0

Pin 37 – PA1

TRANSMODE SWITCH

ENGINE MODE SWITCH

LIGHTS SWITCH

LIGHTS OUT

BRAKE LIGHTS OUT

Page 113: AutoPlug

112

Figure A2-10 555 TIMER CIRCUIT

1

2

3

4

8

7

6

5

2.2K Ohms

22 nF

10 nF

TMR IN

TMR RESET

TMR OUT

5V

5V

Page 114: AutoPlug

113

Figure A2-11 RC FILTER

Figure A2-12 STEERING WHEEL CIRCUIT

100K Ohms

10 uF

+

-

RC IN

+15V

-15V

RC OUT TO TORCS

5V

STEERING WHEEL

BTN3

BTN2

STEER_OUT

BTN1

BTN4

TO TMR IN

TO STR ECU

TO STR ECU

TO STR ECU

TO STR ECU

1A2-11 RC FILTER

Page 115: AutoPlug

114

Figure A2-13 PEDALS CIRCUIT

5V

PEDALS

ACCEL

BRK

TO PEDALS ECU

TO PEDALS ECU

Page 116: AutoPlug

115

A2-14 COMPLETE SYSTEM

Page 117: AutoPlug

116

A3 CONTROL DIAGRAMS

Figure A3-1 ABS/Brakes ECU Software Flow

Figure A3-2 Cabin Control ECU Software Flow

Page 118: AutoPlug

117

Figure A3-3 Cruise Control ECU Software Flow

Figure A3-4 Differential Control ECU Software Flow

Page 119: AutoPlug

118

Figure A3-5 Transmission Control ECU Software Flow

Page 120: AutoPlug

119

A4 ADDITIONAL GRAPHS

A4.1 EXAMPLE ABS/BRAKES OPERATION

Figure A4.1-1 Example ABS/Brakes Operation (FL Wheel)

3 3.5 4 4.5 5 5.5 6 6.5 7

0

150

100

50

200

Time (s)

Wh

ee

l S

pe

ed

(km

/h)

ABS/Brakes Operation: Wheel Speed vs. Brake Command

3 3.5 4 4.5 5 5.5 6 6.5 7

0

50

100

25

75

Ap

plie

d B

rake

Co

mm

an

d (

no

rma

lize

d to

10

0)

Wheel Speed (FL)

Brake Cmd. (FL)

3 3.5 4 4.5 5 5.5 6 6.5 7

0

150

100

50

200

Time (s)

Wh

ee

l S

pe

ed

(km

/h)

ABS/Brakes Operation: Wheel Speed vs. Brake Command

3 3.5 4 4.5 5 5.5 6 6.5 7

0

50

100

25

75

Ap

plie

d B

rake

Co

mm

an

d (

no

rma

lize

d to

10

0)

Wheel Speed (RL)

Brake Cmd. (RL)

Page 121: AutoPlug

120

Figure A4.1-2 Example ABS/Brakes Operation (RL Wheel)

Figure A4.1-3 Example ABS/Brakes Operation (RR Wheel)

3 3.5 4 4.5 5 5.5 6 6.5 7

0

150

100

50

200

Time (s)

Wh

ee

l S

pe

ed

(km

/h)

ABS/Brakes Operation: Wheel Speed vs. Brake Command

3 3.5 4 4.5 5 5.5 6 6.5 7

0

50

100

25

75

Ap

plie

d B

rake

Co

mm

an

d (

no

rma

lize

d to

10

0)

Wheel Speed (RR)

Brake Cmd. (RR)

Page 122: AutoPlug

121

A4.2 PATHOLOGICAL ABS/BRAKES OPERATION

Figure A4.2-1 Pathological ABS/Brakes Operation (FL Wheel)

Figure A4.2-2 Pathological ABS/Brakes Operation (FR Wheel)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Time (s)

Wh

ee

l S

pe

ed

(km

/h)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Ap

plie

d B

rake

Co

mm

an

d (

no

rma

lize

d to

10

0)

Pathological ABS/Brakes: Wheel Speed vs. Brake Command

Wheel (FL)

Brake (FL)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Time (s)

Wh

ee

l S

pe

ed

(km

/h)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Ap

plie

d B

rake

Co

mm

an

d (

no

rma

lize

d to

10

0)

Pathological ABS/Brakes: Wheel Speed vs. Brake Command

Wheel (FR)

Brake (FR)

Page 123: AutoPlug

122

Figure A4.2-3 Pathological ABS/Brakes Operation (RL Wheel)

Figure A4.2-4 Pathological ABS/Brakes Operation (RR Wheel)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Time (s)

Wh

ee

l S

pe

ed

(km

/h)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Ap

plie

d B

rake

Co

mm

an

d (

no

rma

lize

d to

10

0)

Pathological ABS/Brakes: Wheel Speed vs. Brake Command

Wheel (RL)

Brake (RL)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Time (s)

Wh

ee

l S

pe

ed

(km

/h)

2 2.5 3 3.5 4 4.5 5

0

20

40

60

80

100

Ap

plie

d B

rake

Co

mm

an

d (

no

rma

lize

d to

10

0)

Pathological ABS/Brakes: Wheel Speed vs. Brake Command

Wheel (RR)

Brake (RR)

Page 124: AutoPlug

123

Figure A4.2-4 Pathological ABS/Brakes Operation: Large Yaw Rate Error

2 2.5 3 3.5 4 4.5 5

0

50

100

25

75

Time(s)

Ve

hic

le S

pe

ed

(km

/h)

2 2.5 3 3.5 4 4.5 5

0

0.8

1.6

2.4

3.2

Ya

w R

ate

Err

or

(ra

d/s

)

Pathological ABS/Brakes: Vehicle Speed vs. Yaw Rate Error

Vehicle Speed

Yaw Rate Error

Page 125: AutoPlug

124

A4.3 CABIN COMFORT CONTROLLER

Figure A4.3-1 Temperature Controller Simulink Model

Figure A4.3-2 Cabin Comfort Controller Step Response

1Out1

.0008z

z-1

TemperatureDynamics3

Proportional

K Ts

z-1

Integral

1

Gain

K (z-1)Ts z

Derivative

Ambient TemperatureNoise

1

In1Error

0 1 2 3 4 5 6 7 8 9 10-0.2

0

0.2

0.4

0.6

0.8

1

1.2

1.4

Time (s)

Magnitude

Step Response of Cabin Comfort Controller with Additive Random Noise

Page 126: AutoPlug

125

A5 DATASHEETS

BeagleBoard Datasheet. Retrieved from www.beagleboard.org

MC9S12C128 Datasheet. Retrieved from

http://www.datasheetpro.com/7054_view_MC9S12C128_datasheet.html

MCP2551 Datasheet. Retrieved from

http://ww1.microchip.com/downloads/en/DeviceDoc/21667f.pdf

NI DAQ 6229-M Manual. Retrieved from http://www.ni.com/pdf/manuals/371022k.pdf

LM 555 Timer Datasheet. Retrieved from http://www.national.com/ds/LM/LM555.pdf

LM 348 Quad Op-Amp Datasheet. Retrieved from http://www.national.com/ds/LM/LM148.pdf

APS12C128 User Guide. Retrieved from

http://www.ece.cmu.edu/~ece348/labs/docs/APS12C128_module/SLKS12UG_module_user_gui

de.pdf

Page 127: AutoPlug

126

A6 MATHEMATICAL EQUATIONS

Turning radius calculation (Source: http://www.carbibles.com/steering_bible.html):

Rturn=1/2*[Wheeltrack/2 + Wheelbase/sin(theta)]

Theta is the steering angle in radians.

Wheel track is lateral distance between wheels.

Wheel base is longitudinal distance between wheels/axles.

Page 128: AutoPlug

127

A7 ADDITIONAL SCREENSHOTS

A7-1 Raw CAN Info

A7-2 Android Application