Skip to content

Ard Constrain Range

DodaTech 1 min read

In this tutorial, you'll learn about Arduino constrain() Not Clamping Values. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

constrain() does not prevent values from exceeding the expected range.

Quick Fix

Wrong

int val = constrain(raw, 0, 255);  // Works, but only constrains, does not map
Values are clamped but may not be in the desired range if raw is out of bounds.
int raw = analogRead(A0);
// Constrain to 0-255 range after mapping
int val = map(raw, 0, 1023, 0, 255);
val = constrain(val, 0, 255);  // Extra safety
analogWrite(9, val);
Serial.print("PWM: ");
Serial.println(val);
PWM: 127  (safe value between 0 and 255).

Prevention

constrain() clamps a value between a minimum and maximum. It does not rescale or map — use map() for scaling. Typical usage: constrain(map(input, 0, 1023, 0, 255), 0, 255). constrain works with any numeric type (int, float, long).

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### What happens if min > max in constrain()?

constrain() returns min if val < max, max if val > min. The behavior is unexpected if min > max. Always ensure min <= max.

Does constrain() work with float?

Yes. constrain(3.14, 0.0, 5.0) returns 3.14. constrain(10.0, 0.0, 5.0) returns 5.0.

Is constrain() same as CLAMP in other languages?

Yes. It is identical to the clamp() function in C++17 (std::clamp) and other languages.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro