aboutsummaryrefslogtreecommitdiffstats
path: root/docs/source/arduino/constrain.rst
blob: a43b8f896a69e442dabec05acfcce71b4059df70 (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
.. highlight:: cpp

.. _arduino-constrain:

constrain(x, a, b)
==================

Description
-----------

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


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() <arduino-min>`
-  :ref:`max() <arduino-max>`


.. include:: cc-attribution.txt