Math Functions

Lesson 81: Using max() Function

Learn how max() selects the larger of two values for safer limits, comparisons, and control logic.

Progress indicator

Lesson 81 of 81

Learning Objectives

  • Understand what max() does mathematically and how it selects the larger of two values.
  • Learn max() syntax and use it for cleaner, more readable comparison logic.
  • Apply max() in sensor-driven control flows where higher values should dominate decisions.
  • Understand type behavior and conversion risks when comparing mixed numeric types.
  • Avoid common mistakes such as side effects in arguments and wrong helper-function choice.

Concept Explanation

What is max()

max() returns the larger of two values. It is a quick way to select the higher number without writing a full if-else comparison every time.

In embedded projects, this is useful for selecting stronger readings, higher limits, or safer fallback values in one line.

max() Syntax

Basic syntax: max(a, b)

  • max(10, 25) returns 25.
  • max(sensorA, sensorB) returns whichever sensor is higher.
  • If both are equal, returned value is that same number.

You can also use expressions: max(currentValue, minSafeValue) for lower-bound style guards.

How max() Works

  1. Evaluate both input arguments.
  2. Compare first value with second value.
  3. Return whichever value is greater.

Conceptually it behaves like: (a > b) ? a : b.

Comparing Two Values

max() is useful whenever you need a "higher wins" rule, like selecting the stronger sensor reading, larger threshold, or bigger delay among options.

Real example: two light sensors on left/right side; using max() can drive output based on the strongest light detected.

max() with Different Data Types

  • Works commonly with int, long, and floating values.
  • When types differ, implicit conversion rules apply.
  • Keeping both arguments same type improves clarity and avoids surprises.

Beginner rule: cast explicitly when needed, so you control conversion behavior instead of relying on implicit promotions.

When to Use max()

  • Selecting the larger of two sensor inputs.
  • Applying minimum-safe floor values with comparison logic.
  • Building compact decision math in embedded loops.
  • Choosing stronger signal or dominant metric before mapping/output.

Example Code

This example selects the larger sensor value and maps it to LED PWM output.

const int LED_PIN = 2;
int sensorA = 320;
int sensorB = 450;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  // Simulate changing sensor values.
  sensorA = sensorA + 40;
  sensorB = sensorB - 25;

  if (sensorA > 700) sensorA = 250;
  if (sensorB < 180) sensorB = 520;

  int selectedValue = max(sensorA, sensorB);
  int pwmValue = map(selectedValue, 0, 700, 0, 255);
  pwmValue = constrain(pwmValue, 0, 255);

  analogWrite(LED_PIN, pwmValue);

  Serial.print("sensorA: ");
  Serial.print(sensorA);
  Serial.print(" | sensorB: ");
  Serial.print(sensorB);
  Serial.print(" | max: ");
  Serial.print(selectedValue);
  Serial.print(" | pwm: ");
  Serial.println(pwmValue);

  delay(700);
}

Example Code Explanation

  1. Two simulated sensors move in opposite directions so comparison changes over time.
  2. Reset conditions keep values inside a demo loop and prevent drift forever in one direction.
  3. max(sensorA, sensorB) selects the stronger value each cycle.
  4. Selected maximum value is mapped to PWM range (0..255).
  5. constrain() protects mapped output from accidental out-of-range writes.
  6. analogWrite() applies final PWM to LED brightness.
  7. Serial log prints both source values and chosen max for transparent debugging.

What Happens Inside

  1. Both arguments are evaluated before comparison result is produced.
  2. CPU performs numeric comparison between argument A and B.
  3. Function returns whichever value is greater (or either if equal).
  4. Returned maximum feeds mapping and output stages.
  5. Hardware output then reflects the strongest input source for that cycle.

Common Mistakes with max()

  • Passing expressions with side effects (like i++) into max().
  • Mixing incompatible types and assuming no conversion occurs.
  • Using max() when min() or constrain() logic is actually needed.
  • Comparing values in different units without normalization first.
  • Using max() as a clamp replacement where full boundary control is required.

Best Practices for max()

  • Keep max() arguments simple variables when possible.
  • Use same data type on both arguments for predictable behavior.
  • Log compared values during testing to confirm decision logic.
  • Document why “higher wins” is correct for your specific control scenario.
  • Pair max() with map()/constrain() when selected values feed hardware outputs.

Try it now

Open the simulator workspace and observe how max() chooses the dominant sensor value.

Run in Simulator