Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

iAccelerate

This article shows how to build a .NET application using an accelerometer to measure the performance of a vehicle. An accelerometer is an instrument that is used for measuring acceleration. By using basic physics equations, we can derive a vehicle's current speed, distance traveled, horsepower, and other performance metrics from the acceleration of the vehicle. iAccelerate is solely for use in a vehicle on a closed course or on private property while under the supervision of a certified emergency care provider. As a reminder, please always wear your safety belt.
Clarity Consulting

Difficulty: Intermediate
Time Required: 6-10 hours
Cost: $50-$100
Software: Visual Basic or Visual C# Express Editions
Hardware: Analog Devices ADXL320
Download: Download

Introduction

I have had a passion for computers and cars for as long as I can remember. Ever since I was little, I have been able to name the make and model of almost any car on the road. I have been around computers since I was young, and can still remember the day I wrote (read: “copied out of a book”) my first program in BASIC for IBM's PCjr. Twenty years later, these same interests coupled with an accelerometer played a role in the development of iAccelerate. iAccelerate displays accurate vehicle performance data from calculations performed 20-30 times per second. The data that is provided can be used to check if your car actually does benefit from a higher octane fuel, or to check if a new exhaust system has increased the horsepower as much as the manufacturer claims (or just makes a lot more noise). The article will first give you some background on what an accelerometer is, and show how you can use it to calculate performance data. An explanation of the development of iAccelerate will follow, describing the calculations and formulas used in code and the factors considered during development. Finally, I will demonstrate how iAccelerate works by walking you through a typical test scenario and comparing the results of the test to the results gathered from reputable sources to determine the accuracy of the data.

Background

In the abstract, I explained that an accelerometer is an instrument that is used to measure acceleration. Accelerometers are commonly used in many different types of applications. For example, they are used to determine if an airbag should be deployed during a crash, or to detect when your laptop has been dropped to prevent hard drive damage. Also, both the Nintendo Wii and PlayStation 3 controllers use accelerometers to calculate how you are holding or moving the controller. If you took physics class in high school or college, you may remember studying kinematics or dynamics. Together, these two areas of mechanics make up the foundation for iAccelerate. By using a few simple physics equations and an accelerometer, you can determine both the velocity (mph) and distance traveled (miles) of a car, assuming it is at a complete stop when the measurements are started. This assumption is important because acceleration is the rate of change of velocity with respect to time. For example, if we are sitting at 0 mph and we measure a change in acceleration with our accelerometer then we must be moving now since acceleration cannot occur without a change in velocity. We can determine the exact value of the car's velocity and distance traveled by using derivations of the following two equations:

Velocityfinal = Velocityinitial + Acceleration × Time

Distance = 1/2 (Velocityfinal + Velocityinitial ) × Time

Once we obtain these values, we can use a computer to calculate virtually any metric relating to a car's performance. The following must hold true for iAccelerate to provide accurate data: the accelerometer provides both the direction and magnitude of the acceleration; we are able to calculate the time spent accelerating; we were not moving when we started timing. Using iAccelerate, we can measure 0-60 mph (acceleration), 60-0 mph (braking distance), lateral acceleration (handling), ¼-mile time (acceleration), and much more. For example, if we provide the vehicle's weight, other measurements such as horsepower and torque can be calculated. The accuracy of the measurements for horsepower and torque can be improved significantly by using the vehicle's coefficient of drag to account for the air resistance incurred on the vehicle. The accuracy of the other measurements should theoretically be identical to a measurement taken with a radar gun, or from the use of a 5th wheel. In practice, however, factors such as the earth's gravity will introduce some margin of error. You will obtain the most accurate measurements by testing on a flat surface.

Development

This application was developed using the 2005 Express Editions of VB.NET and Visual C#, which are available free of charge from the link provided at the beginning of this article. I created the project with each class being as loosely coupled from one another as possible. The project has a class called CarCalculator that is responsible for all of the necessary physics calculations and handles the conversion of the calculated results to U.S. customary units. This class is instantiated by calling the constructor with the gross weight (in pounds) of the car tested as its parameter. Most properties of this class return their value in U.S. customary units but are set internally using the metric system of units, as these are the native units the class uses in the calculations. The following code is an example of how the CarCalculator stores weight privately (in kilograms) and how the class exposes this value publically (in pounds).

The constructor:

C#

public CarCalculator(double weight)
{
     this.Weight = weight;
     this.reset();
}

VB.NET

 

Public Sub New(ByVal weight As Double)
    Me.Weight = weight
    Me.reset()
End Sub 

The Weight property of the class:

C#

public double Weight
{
    get     
    {
         return _weight;
    }
    set
    {
         _weight = (value / POUNDS_PER_KG);
    }
}
VB.NET
 
Public Property Weight() As Double
    Get
        Return _weight
    End Get
    Set(ByVal Value As Double)
        _weight = Value / POUNDS_PER_KG
    End Set
End Property 

 

The CarCalculator uses an event model to notify consumers during a test. The SpeedReachedCheckpoint events are fired when the CurrentSpeed property reaches one of the speeds (e.g. 60 mph) added by the user in the Setup form. This functionality is shown in the following code snippets.

 

C#

if (_checkPoints != null)
{
    foreach (double speed in _checkPoints)
    {
        if (_lastCheckpoint != Math.Floor(speed)
             &&  (Math.Floor(CurrentSpeed) == Math.Floor(speed)))
        {
            SpeedReachedCheckpoint(_totalTime, CurrentSpeed);
            _lastCheckpoint = Math.Floor(CurrentSpeed);
        }
     }
 }

VB.NET

 

If Not _checkPoints Is Nothing Then
    For Each speed As Double In _checkPoints
        If lastCheckpoint <> Math.Floor(speed) AndAlso Math.Floor(CurrentSpeed) = Math.Floor(speed) Then
            RaiseEvent SpeedReachedCheckpoint(_totalTime, CurrentSpeed)
            lastCheckpoint = Math.Floor(CurrentSpeed)
        End If
    Next
End If

The next class I will discuss, called Setup, is instantiated only when the application first loads. It is solely responsible for handling all of the data that is user configurable and validating input for any user-supplied settings, such as ”speed reached checkpoints”, vehicle and passenger weights, and the car's coefficient of drag (if horsepower is being measured).

Figure 1 (below) shows the Setup form.

The next class, called Main, is responsible for handling all of the input and output to and from the CarCalculator class. The accelerometer raises an event providing the current acceleration value to the wired event handler 20-30 times per second. This value, along with the amount of time that has elapsed since the last time the event was raised, is passed into a public method in the CarCalculator class. This method uses these two values to perform all of the calculations, and sets the results of the calculations to properties in the CarCalculator class. Since this event is fired so frequently, the Main class/form only displays these results on the screen four times per second. The user can also configure the application to write the results to a CSV file for further analysis. In this case, a row is added to a file every time this event is fired. Consequently, the resulting file will contain the results of every calculation made by the CarCalculator. This file can be opened with Excel to create charts and graphs so the data can be easily interpreted.

This event handler is very hard to test or debug because all of the calculations performed are based on time. For instance, if you set a breakpoint in the event handler so you can evaluate an expression, the Stopwatch object responsible for measuring the elapsed time will continue to tick away when the debugger reaches the breakpoint – rendering it nearly impossible to evaluate the expression the next time the event is fired. The elapsed time value that the CarCalculator relies on will now also include the time that it took to debug, ultimately resulting in inaccurate output.

 

private void accel_AccelerationChange(object sender, AccelerationChangeEventArgs e)
 
{
    // pseudo code
    time = SetElapsedTimeSinceLastCalculation;
    
    // when a breakpoint is set to check the results of the following
    // statement, the time value will be increasing, causing inaccurate
    // data the next time this code is executed
 
    CalculateVehiclePerformance(time, e.Acceleration);
    // example calculation (used in the above method): 
    // currentSpeed = lastSpeed + (((e.Acceleration + _lastAcceleration) * time) / 2);
 
    DisplayResults;
}

 

There is too much code to cover here, and I have already outlined the location and functionality of the methods that are pertinent to accurate data output. I highly recommend reading through the source code to fully understand the program. I will now demonstrate the application using the data from my RX-8's test run.

Final Product

To use this application, you will need a vehicle to test, a notebook computer, and an accelerometer. You can purchase a USB accelerometer from http://www.trossenrobotics.com/ for less than $70. A .NET assembly is also available for download from this site so you can start coding without having to write your own interface for the accelerometer. Most, if not all, RS232 accelerometers that I found would work just as well but would require much more development time. In addition, since you would be using the accelerometer from within the confines of a car, being able to quickly plug and unplug the device is essential. From information gathered from various forums, a tri-axis USB model is currently in development, which you could use to negate the error caused by the acceleration due to gravity that was mentioned earlier. I will now walk you through a scenario where the 0 to 60 mph time of my RX-8 is tested.

Setting the weight, output types, and checkpoints:

Figure 1 – Setting up the calculator

The frontal area of your car can be found by having a friend park behind you with their lights on (park your car's nose 5 feet or so from a wall or building) and then trace the shadow. Measure the shadow's area using a metric ruler. The current default setting is for an older RX-7 that I found data for. I am sure my car is a little bigger, so this probably has an effect on the resulting horsepower value. Since horsepower is the only calculation that uses this setting, all other data will be accurate – so in other words, you can leave this setting as the default if you do not know your car's frontal area. The other defaulted setting is the coefficient of drag, which is defaulted to the average value found for about ten sports cars. If you would like to use your car's specific value, you can find it by running your car's name through a search engine with the word “drag” next to it.

 

Main output screen (after start has been clicked):

Figure 2 – The application is waiting for the change of acceleration to exceed the value entered during the setup stage (.09g) before timing will begin.

 

Main output screen results (10 seconds elapsed – timing over):

Figure 3 – The results of a 0-60 test on a 2004 Mazda RX-8 (6-speed)

If you noticed, the 0-60 time arrived in 5.871x seconds. Two magazines quoted it right around 5.8 s while another quoted it at 6.5 s.

 


Excel output (every calculation from the 10 second run is in this file – much more detailed than the screen's output):

Figure 4 – A CSV file opened with Excel allowing for analysis of all of the calculated data (e.g. horsepower graph)

 

Conclusion

I have tried to make this project as easy to modify as possible by keeping the data calculations separate from the display of calculated data to the user. This allows for greater flexibility when developing iAccelerate on other platforms. For example, rewriting this application for use on a Windows Mobile Smartphone would be cool, as you would not have to worry about breaking your laptop when you try to beat your cornering record. The processing power required to perform the needed calculations and output the results fast enough was unknown during design, so the decision to build a standard WinForm application was predisposed. If anyone redesigns this for use on a cell phone (or redesigns it at all), please provide some feedback on how it turns out. The use or modification of this software for educational or testing purposes is strongly encouraged. The developer prohibits the use of this source code and/or assembly for monetary and/or personal gain. If errors are discovered in any of the code or the calculations that were used within iAccelerate, please feel free to contact me at the following email address: mharkabus@claritycon.com

Tags:

Follow the Discussion

  • Mike HarkabusMike Harkabus

    I recently published an article that shows how to build a Windows Forms application using an accelerometer...

  • Bob HarkabusBob Harkabus

    Is this what you do with your spare time...? You should be out shooting. (kidding of course)

    Very cool.

  • imikeimike

    Hi Mike. Interesting project. I`m working on a similar project involving detecting the position with accelerometers. I do not have a phidgits accelerometer kit now. I was wonderring how did u work for the noise cacellation, or there was a little noise, it is cancelled within the phidget ?

    Thank You.

  • Dale ScottDale Scott

    I can't seem to find the code package for download. The Download link sends me to Channel 9, but the only thing I saw there was a link back to here. Help?

  • Mike HarkabusMike Harkabus

    iMike, please email me so I can answer your questions.

    Sorry for the late response...

  • Martin de LeonMartin de Leon

    Hi mike, i have a couple of questions about iAccelerate, but your email on this page doesnt seem to work. Do you have any alternate emails? thanks!

  • MikeMike

    Martin, you can email me at mharkabus@gmail.com

  • LeoLeo

    Am looking for the link to the source code....  was it removed?

  • Clint RutkasClint I'm a "developer"

    @Leo, the link is functional on Channel9, it says "Download: ".

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.