Skip to main content
emobility.academy
B.Tech / BEVehicle dynamics & safetyIntermediate About 6 weeksKit only

Driver Behaviour Scoring from Accelerometer and Gyroscope Data

Build a driver-behaviour scorer that detects harsh acceleration, braking and cornering from the MPU6050, logs events to the kit's SPI flash and computes a trip score. A Python tool reads the log over UART and plots each trip.

Uses: I2C · UART · SPI

The problem

Fleet operators of electric vehicles want to coach riders, because smooth riding saves energy, reduces wear and lowers accident risk. Scoring needs dependable event detection and a log that survives power loss.

Objectives

  • Sample the MPU6050 at 100 Hz and detect longitudinal and lateral harsh events
  • Compute a transparent trip score from event counts and severity
  • Store events and trip summaries in SPI flash with a robust log format
  • Export logs over UART and visualise them in Python

What you need

From the EV Embedded Development Kit

  • STM32F103C8T6 microcontroller unit (Arm Cortex-M3)
  • 3-axis accelerometer and gyroscope (MPU6050, I2C)
  • SPI flash memory
  • Serial UART interface
  • 4×3 matrix keypad
  • 16×2 LCD
  • RGB LEDs and a buzzer

Software

  • STM32CubeIDE with HAL I2C, SPI and UART
  • Embedded C
  • Python with pyserial, pandas and matplotlib

Extra parts

None. Everything this project needs is on the kit.

Key concepts

Harsh cornering
Cornering is seen as lateral acceleration and yaw rate; high values for a sustained time indicate aggressive turning.
Event severity
Each event is scored by its peak and duration, so a mild harsh brake costs fewer points than a very hard one.
SPI flash log
Flash is erased in sectors and written in pages; an append-only log with record headers and CRCs survives power loss mid-write.
JEDEC ID
Sending command 0x9F to a serial flash returns its manufacturer and device ID, which confirms the chip and its size.

Step-by-step guide

  1. 1

    Requirements and scoring rules

    Define the three event types, harsh acceleration, harsh braking and harsh cornering, with initial thresholds and qualification times. Define the score: each trip starts at 100 and loses points for each event according to its severity, normalised by trip duration so long trips are not penalised for length. Keypad * starts a trip and # ends it. Write worked examples of the scoring so the whole team calculates the same result.

    Checkpoint: A written scoring rule with worked examples.

  2. 2

    Board setup

    Use the DIP switches to enable the MPU6050, SPI flash, keypad, LCD and UART. In CubeMX configure the 72 MHz clock, I2C at 400 kHz, SPI for the flash with a GPIO chip select, UART at 115200 baud and a timer for 100 Hz sampling. Send the JEDEC ID command 0x9F to the flash and check the reply against the chip's datasheet, which also tells you its size, sector size and page size.

    Checkpoint: The flash returns a valid JEDEC ID to command 0x9F.

  3. 3

    IMU sampling and calibration

    Read the MPU6050 at 100 Hz from the timer interrupt. Calibrate the accelerometer offsets and the gyro bias with the board at rest, and align the axes so x is forward, y is lateral and z is vertical; mark the orientation on the board. Low-pass filter the signals used for event detection to remove vibration. Check that the forward and lateral readings are near zero at rest after calibration.

    Checkpoint: Rest readings are near zero on x and y and gyro bias is removed.

  4. 4

    Event detection

    Detect each event type when its signal, forward acceleration for acceleration and braking, lateral acceleration and yaw rate for cornering, exceeds its threshold for the qualification time. Record the start time, duration and peak value, and apply a hold-off after each event to avoid counting it twice. Test with deliberate movements of each type and check they are classified correctly and that gentle movements produce no events.

    Checkpoint: Deliberate movements of each type are detected and classified correctly.

  5. 5

    Flash log format

    Design the log records: a type byte, a length, a timestamp in milliseconds since trip start, the payload and a CRC-16. Append records page by page into erased flash, erasing sectors ahead of the write position. At start-up find the end of the log by scanning for erased bytes. Test by removing power during logging: after restart every complete record must be present and any partial record must fail its CRC and be skipped.

    Checkpoint: Power is removed during logging, and after restart the log contains every complete record and no corrupt ones.

  6. 6

    Trip scoring

    When the trip ends, compute the score from the logged events using the rules from the first step, write a trip summary record with the score and event counts, and show the result on the LCD. Set the RGB LED by score band, for example green, amber or red. Recompute the scores of several trips by hand from the logged events and check they match the firmware result exactly.

    Checkpoint: Scores match hand calculations from the logged events.

  7. 7

    UART export

    Add a command on the UART to dump the whole log, either as compact binary or as text, with a header that tells the PC how many records follow. Add an erase command that only runs after the user confirms it on the keypad, so the log cannot be wiped by a stray command. Check on the PC that every record arrives and that all CRCs are valid.

    Checkpoint: The PC receives the full log and record CRCs all check.

  8. 8

    Python viewer

    Write a Python tool with pyserial and pandas that requests the log, parses the records, lists the trips and plots each one: a timeline of events coloured by type and severity, the acceleration traces around each event if you logged them, and the trip score. Compare a plot with what you remember of the trip to check it makes sense, and save plots for the report.

    Checkpoint: Plots match what happened during a recorded trip.

  9. 9

    Testing

    Plan test trips as a written sequence of smooth and harsh manoeuvres, then carry them out by moving the board on a trolley or by hand, noting the time of each planned event. Compare the detected events with the plan, counting correct detections, misses, false events and wrong classifications. If you mount the kit on a bicycle, power it safely, secure it firmly and test only in a safe, quiet place. Repeat over several trips.

    Checkpoint: A table comparing planned and detected events over several trips.

  10. 10

    Report

    Write up the event rules, the flash log format and its power-loss behaviour, the scoring method with worked examples, the test results and the Python viewer. Discuss the limitations honestly: thresholds tuned on a trolley or by hand will need retuning on a real vehicle, and the IMU's mounting orientation must be known and fixed. Include sample trip plots, the detection results table and a short demonstration video.

    Checkpoint: Report and demonstration.

Testing & validation

  • Flash JEDEC ID and power-loss log integrity test
  • Event detection accuracy against planned manoeuvres
  • Score recomputed by hand from logs

Expected results

A driver-behaviour scorer that detects and grades harsh manoeuvres, keeps a power-safe log in SPI flash and produces trip scores and plots on the PC.

Take it further

  • Add RTC timestamps to trips
  • Upload summaries over a Bluetooth module add-on to a phone
  • Train a small classifier on logged features and compare it with threshold rules

Viva and review questions

How does the log survive power loss?

Each record carries a length and CRC and is appended to erased flash, so an interrupted write leaves an incomplete record that fails its CRC and is ignored.

Why normalise the score by trip duration?

Otherwise long trips would score worse simply because there is more time for events.

How is cornering detected?

From sustained lateral acceleration and yaw rate above thresholds, with the board aligned to the vehicle axes.

Related EV projects

All 100 EV projects