Skip to content

constrain

gicking edited this page Feb 10, 2018 · 4 revisions

back to Command Reference / Math

Description

Clips a number to a specified value range.

Notes:

  • Because of the way the constrain() function is implemented, using other functions inside the brackets may lead to incorrect results. For example, avoid constrain(x++,a,b).

Inclusion

  • defined in misc.h
  • auto-loaded in main_general.h
  • no #define required

Syntax

y = constrain(x, a, b)

Parameters

  • input:

    • x: the number to constrain
    • a: lower range limit
    • b: upper range limit
  • output:

    • none

Returns

  • x: if x is between a and b
  • a: if x is less than a
  • b: if x is greater than b

Example Code

The below code prints the values from -10..10, clipped to [-5;5].

#include "main_general.h"
#include "uart1.h"
#include "putchar.h"
    
void setup()
{
  int i;

  // init UART1 to 115.2kBaud, 8N1, full duplex
  UART1_begin(115200);

  // use UART1 for printf() output
  putcharAttach(UART1_write);

  // allow terminal to launch
  sw_delay(1000);

  // print values
  for (i=-10; i<=10; i++)
    printf("%d  %d\n", i, constrain(i,-5,5));

}

void loop()
{
  // dummy
}

Relevant Tutorial

  • tbd

See also

Clone this wiki locally