aboutsummaryrefslogtreecommitdiffstats
path: root/docs/source/lang/api/constrain.rst
blob: 28af1e324518b94927877affa068edeb2b025a79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
.. highlight:: cpp

.. _lang-constrain:

constrain()
===========

(Macro) Constrains a number to be within a range.

Syntax
------

::

    constrain(x, a, b)


Parameters
----------

**x**: the number to constrain

**a**: the lower end of the range

**b**: the upper end of the range

Returns
-------

**x**: if **x** is between **a** and **b**

**a**: if **x** is less than **a**

**b**: if **x** is greater than **b**

Example
-------

::

    // limits range of sensor values to between 10 and 150:
    sensVal = constrain(sensVal, 10, 150);


Warning
-------

Because of the way ``constrain()`` is implemented, avoid using other
functions or causing side effects inside the parentheses, as it may
lead to incorrect results::

    constrain(x,a++,b);   // avoid this - yields incorrect results

    constrain(x,a,b);     // use this instead-
    a++;                  // keep other math outside constrain()

Arduino Compatibility
---------------------

Maple's implementation of ``constrain()`` is compatible with Arduino.

See Also
--------

-  :ref:`min() <lang-min>`
-  :ref:`max() <lang-max>`

.. include:: /arduino-cc-attribution.txt