trunc()

[Math]
double trunc(double x);

Description

Returns the value of x truncated to the nearest integer not larger in absolute value.

Parameters

x: The value to calculate the truncated value.

Returns

The value of x truncated to the nearest integer not larger in absolute value as a floating-point number.

Example Code

The code reads the value of a potentiometer connected to pin IN and places the truncated value of x on pin OUT.

void setup() {
    pinLabel(0, "IN");   // set the label of pin 0 to "IN"
    pinLabel(1, "OUT");  // set the label of pin 1 to "OUT"
    pinMode(1, OUTPUT);  // set pin 1 as output

    pinLabel(2, "VCC");  // set the label of pin 2 to "VCC"
    powerPin(2);         // set pin 2 as power pin
    pinLabel(3, "GND");  // set the label of pin 3 to "GND"
    groundPin(3);        // set pin 3 as ground pin
}

void loop() {
    // read the value of the potentiometer
    int val = analogRead(0);
    // map the value of the potentiometer from 0 to 1023
    // to the range of -5 to 5
    double x = map(val, 0, 1023, -5, 5);
    // calculate the truncated value of x
    double y = trunc(x);
    // map the value of y from -5 to 5 to 0 to 1023
    int pwm = (int) map(y, -5, 5, 0, 1023);
    // write the value of pwm to pin 1
    analogWrite(1, pwm);
}