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.
Right
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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro