Main Site Documentation

Constrain function arduino


#1

Hi,

In the universe NETMF / GHI is there any function equal to constrain the arduino?

Thanks,

Alexandre
From Brazil


#2

What does this function do?


#3

constrain function make this:

http://arduino.cc/en/Reference/constrain


#4

constrain(x, a, b)

Description
Constrains a number to be within a range.

Parameters
x: the number to constrain, all data types
a: the lower end of the range, all data types
b: the upper end of the range, all data types

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

You can write this function easily.

Eric


#5

Erick, see my function:

static int constrain(int x, int a, int b)
{
int max = System.Math.Max(a, b);
int min = System.Math.Min(a, b);
int result = 0;

        if (x > min && x < max)
            result = x;
        else if (x < min)
            result = min;
        else if (x > max)
            result = max;

        return result;

}


#6

You only need to check if it is less than a or greater than b. You can also eliminate Min/Max dependency by comparing a and b.


#7

You can implement this function as an extension for each numeric data type like so…



// Required for NETMF to recognized extension methods
namespace System.Runtime.CompilerServices
{
  [AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
  public sealed class ExtensionAttribute : Attribute { }

}

public static class Extensions
{
  public static int Constrain (this int x, int a, int b)
  {
    return x < a ? a : (x > b ? b : x);
  }

  public static double Constrain (this double x, double a, double b)
  {
    return x < a ? a : (x > b ? b : x);
  }

  // continued... define an extension for all numeric data types
}


#8

@ ransomhall

given a < b,but not in general case


#9

I got too excited about the “one liner” :wink: So what happens in the arduino function when a>b? The help link above does not provide details in this case. I’m not sure what the most logical answer would be. switch a & b values?