Skip to main content
emobility.academy
M.TechEmbedded software architectureAdvanced About 8 weeksKit only

MISRA C Compliance and Static Analysis of EV Firmware

Students take an existing EV firmware project from the kit, run static analysis with MISRA C checks, classify and fix violations, write justified deviations, and measure the effect on defects found, code size and timing.

Uses: UART

The problem

Automotive firmware is expected to follow coding guidelines such as MISRA C and to pass static analysis before release. Student and prototype code often has hidden undefined behaviour, implicit conversions and unchecked returns. Learning to apply MISRA C properly, not just silence warnings, is a valued industry skill.

Objectives

  • Set up a repeatable static analysis pipeline for STM32 firmware.
  • Run MISRA C:2012 checks and classify violations by rule category and cause.
  • Fix violations in application code and write a deviation record where a fix is not appropriate.
  • Seed known defects to measure what the tools catch.
  • Measure changes in violations, code size and execution time.

What you need

From the EV Embedded Development Kit

  • STM32F103C8T6 main controller
  • Serial UART interface
  • Analog potentiometer input
  • Motor driver for PWM motor-control experiments
  • 16×2 LCD
  • 4×3 matrix keypad

Software

  • STM32CubeIDE with GCC
  • Cppcheck with its MISRA addon (rule texts must come from a licensed copy of the MISRA C guidelines)
  • GCC warnings (-Wall -Wextra -Wconversion) and clang-tidy
  • Optional commercial analysers if the institute has licences
  • Python 3 for report generation
  • git for tracking changes

Extra parts

None. Everything this project needs is on the kit.

Key concepts

MISRA C:2012 rule categories
Rules are mandatory, required or advisory. Required rules may be deviated with a documented justification; mandatory rules may not.
Deviation record
A written justification for not following a rule in a specific place, with the risk and how it is controlled. It is part of the compliance evidence.
Undefined behaviour
C constructs whose result the standard does not define, such as signed overflow or out-of-bounds access. Many MISRA rules exist to prevent them.
Essential type model
MISRA's way of classifying expressions (boolean, signed, unsigned, character, enum, floating) to catch risky implicit conversions.
Third-party code scope
Generated HAL and CMSIS code is usually treated as adopted code, analysed separately or excluded with justification, while application code is held to the full rules.

Step-by-step guide

  1. 1

    Choose the code base and define the scope

    Pick an existing kit project with real logic, for example a throttle-to-PWM motor controller with LCD and keypad, or a BMS protection program. Freeze a baseline in git. Define the scope: application files are fully analysed; CubeMX-generated HAL and CMSIS files are adopted code handled separately. Write a compliance plan stating the guideline version, tools and how deviations are approved.

    Checkpoint: A tagged baseline commit and a one-page compliance plan agreed with your guide.

  2. 2

    Set up the analysis pipeline

    Install Cppcheck and run it with the MISRA addon, passing the project's include paths and defines (for example STM32F103xB and USE_HAL_DRIVER) so it parses like the compiler. Provide the rule texts file from your licensed MISRA document. Add GCC with -Wall -Wextra -Wconversion and run clang-tidy. Wrap everything in a script that produces one combined report. Record every tool version in the report.

    Checkpoint: A single command produces a report for the baseline with no tool configuration errors.

  3. 3

    Build and confirm the firmware

    Build the baseline and run it on the kit to confirm it works: potentiometer controls PWM duty to the motor driver, the LCD shows values and keypad modes work. Record flash and RAM usage from the map file and measure the main control loop's execution time with the DWT cycle counter so later changes can be compared. Write these functional checks down as a test sheet you will repeat after every round of fixes.

    Checkpoint: Recorded baseline behaviour, flash, RAM and loop timing.

  4. 4

    Classify the baseline violations

    Export violations to a spreadsheet with rule number, category, file, line and a cause label such as implicit conversion, missing default, side effect in condition, unchecked return, magic number, or pointer arithmetic. Count violations per rule and per thousand lines of code. Separate application code from adopted code. Check a sample of violations by hand to estimate how many are false positives, and note them separately. This keeps later before-and-after comparisons honest and shows which tool findings needed human judgement.

    Checkpoint: A classified table and a Pareto chart of the most frequent rules in application code.

  5. 5

    Seed known defects

    Before fixing, create a branch with deliberately inserted defects: an uninitialised variable, signed overflow in a duty calculation, an array index off by one, an ignored HAL return value, a missing break, and an assignment inside an if condition. Run the pipeline and record which tools catch which defects. Also record false positives near the seeded code. Keep the seeding branch separate from the fixing work so the detection results can be reproduced later with the same tool versions.

    Checkpoint: A detection matrix showing each seeded defect against each tool.

  6. 6

    Fix violations in application code

    Work rule by rule, starting with mandatory and required rules. Use fixed-width types from stdint.h, explicit casts where conversions are intended, braces on every if and loop body, a single point of exit where your plan requires it, default cases in every switch, checked HAL return values and named constants. Re-run analysis after each group of changes and commit separately.

    Checkpoint: Required and mandatory violations in application code fall to zero or to documented deviations.

  7. 7

    Write deviation records

    Some rules are hard to meet with HAL-style code, for example casts between integers and pointers for register access. For each, write a deviation: rule, location, reason, risk, and how the risk is controlled. Mark them in code with a consistent comment format linked to the record. Have another team member review each deviation, as an approval step would in industry, and record the reviewer's name and date. Count deviations by rule so the report shows where the code base most often conflicts with the guidelines.

    Checkpoint: A deviation register with every remaining required-rule violation justified.

  8. 8

    Check behaviour, size and timing

    Rebuild, flash and repeat the baseline functional tests. Compare flash, RAM and control-loop execution time against the baseline. Investigate any change in timing or size and explain it. Run the same functional test sheet as before on the kit: throttle sweep, keypad modes, display values and any fault handling. Measure flash, RAM and the control-loop cycles with the DWT counter at the same optimisation level, and explain any difference, for example extra checks on HAL return values.

    Checkpoint: Functional tests pass and a table compares size and timing before and after.

  9. 9

    Automate the checks

    Make the pipeline run on every commit with a git pre-commit hook or a simple script, failing if new required-rule violations appear without a deviation. This is how teams keep compliance once it is reached. Keep a baseline file of accepted findings and deviations, so the script reports only new issues. Run it on a fresh clone to make sure it does not depend on local settings, and document how to run it in the project readme so every team member uses the same checks.

    Checkpoint: Introducing a new violation in a test commit is blocked by the script.

  10. 10

    Analyse and report

    Present the baseline profile, the fixes, the deviations, the seeded-defect results and the cost of compliance. Discuss what static analysis cannot prove, and how it fits with testing and code review in an ISO 26262-style process, without claiming certification. Include the classified violation tables before and after, the Pareto chart, the deviation register, the detection matrix and the size and timing comparison. Draw practical conclusions, such as which rules gave most value for this code base and which tool findings needed most manual review.

    Checkpoint: A report with before-and-after metrics, the deviation register and the detection matrix.

Testing & validation

  • Firmware behaviour unchanged after fixes, shown by repeated functional tests.
  • Violation counts before and after, per category, from the same tool configuration.
  • Seeded-defect detection rates per tool.
  • Automated check blocks new unjustified violations.

Expected results

A MISRA-checked version of an EV firmware project with a classified violation profile, deviation register, tool detection comparison and measured size and timing impact.

Research angle for your M.Tech thesis

Research questions: which MISRA rule groups catch the defects that occur in student and prototype EV firmware, how do open-source and commercial analysers compare on seeded defects, and what does compliance cost in size and timing on a Cortex-M3? Metrics: violations per KLOC by category, seeded-defect detection rate and false positives per tool, flash, RAM and WCET changes. Baseline: the original code and compiler warnings alone. A strong thesis would use several code bases and a documented seeding method so the comparison can be repeated.

Take it further

  • Add unit tests and coverage measurement alongside static analysis.
  • Compare two analysers on the same code and seeded defects.
  • Apply the same process to FreeRTOS-based firmware and its configuration.

Viva and review questions

What is the difference between a required and a mandatory rule?

Required rules may be deviated with a documented justification; mandatory rules may never be deviated.

Why not just suppress the warnings?

Suppression hides risk without evidence. A fix or a justified deviation shows the issue was understood and controlled.

How did you treat the HAL code?

As adopted third-party code, analysed separately and excluded from application metrics with a stated justification.

Does MISRA compliance make the firmware safe?

No. It reduces certain classes of defects; testing, reviews and a safety process are still needed.

Related EV projects

All 100 EV projects