Example #1
0
/**
 * Configures this IO pin as an analog/pwm output if it isn't already, configures the period to be 20ms,
 * and sets the duty cycle between 0.05 and 0.1 (i.e. 5% or 10%) based on the value given to this method.
 *
 * A value of 180 sets the duty cycle to be 10%, and a value of 0 sets the duty cycle to be 5% by default.
 *
 * This range can be modified to fine tune, and also tolerate different servos.
 *
 * @param value the level to set on the output pin, in the range 0 - 180
 * @param range which gives the span of possible values the i.e. lower and upper bounds center ± range/2 (Defaults to: MICROBIT_PIN_DEFAULT_SERVO_RANGE)
 * @param center the center point from which to calculate the lower and upper bounds  (Defaults to: MICROBIT_PIN_DEFAULT_SERVO_CENTER)
 * @return MICROBIT_OK on success, MICROBIT_INVALID_PARAMETER if value is out of range, or MICROBIT_NOT_SUPPORTED
 * if the given pin does not have analog capability.
 */
int MicroBitPin::setServoValue(int value, int range, int center)
{
    //check if this pin has an analogue mode...
    if(!(PIN_CAPABILITY_ANALOG & capability))
        return MICROBIT_NOT_SUPPORTED;

    //sanitise the servo level
    if(value < 0 || range < 1 || center < 1)
        return MICROBIT_INVALID_PARAMETER;

    //clip - just in case
    if(value > MICROBIT_PIN_MAX_SERVO_RANGE)
        value = MICROBIT_PIN_MAX_SERVO_RANGE;

    //calculate the lower bound based on the midpoint
    int lower = (center - (range / 2)) * 1000;

    value = value * 1000;

    //add the percentage of the range based on the value between 0 and 180
    int scaled = lower + (range * (value / MICROBIT_PIN_MAX_SERVO_RANGE));

    return setServoPulseUs(scaled / 1000);
}
Example #2
0
 //% help=pins/servo-set-pulse weight=19
 //% blockId=device_set_servo_pulse block="servo set pulse|pin %value|to (µs) %micros"
 //% value.fieldEditor="gridpicker" value.fieldOptions.columns=4
 //% value.fieldOptions.tooltips="false"
 void servoSetPulse(AnalogPin name, int micros) {
     PINOP(setServoPulseUs(micros));
 }