servo.c 12.2 KB
Newer Older
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
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

Damien George's avatar
Damien George committed
27 28
#include <stdio.h>

29
#include "py/runtime.h"
30 31 32
#include "py/mphal.h"
#include "pin.h"
#include "genhdr/pins.h"
33
#include "timer.h"
Damien George's avatar
Damien George committed
34 35
#include "servo.h"

36 37 38 39 40 41 42 43 44
// This file implements the pyb.Servo class which controls standard hobby servo
// motors that have 3-wires (ground, power, signal).
//
// The driver uses hardware PWM to drive servos on pins X1, X2, X3, X4 which are
// assumed to be on PA0, PA1, PA2, PA3 but not necessarily in that order (the
// pins PA0-PA3 are used directly if the X pins are not defined).
//
// TIM2 and TIM5 have CH1-CH4 on PA0-PA3 respectively.  They are both 32-bit
// counters with 16-bit prescaler.  TIM5 is used by this driver.
Damien George's avatar
Damien George committed
45

46 47 48 49
#define PYB_SERVO_NUM (4)

typedef struct _pyb_servo_obj_t {
    mp_obj_base_t base;
50
    const pin_obj_t *pin;
51 52 53 54 55 56 57
    uint8_t pulse_min;          // units of 10us
    uint8_t pulse_max;          // units of 10us
    uint8_t pulse_centre;       // units of 10us
    uint8_t pulse_angle_90;     // units of 10us; pulse at 90 degrees, minus pulse_centre
    uint8_t pulse_speed_100;    // units of 10us; pulse at 100% forward speed, minus pulse_centre
    uint16_t pulse_cur;         // units of 10us
    uint16_t pulse_dest;        // units of 10us
58
    int16_t pulse_accum;
59
    uint16_t time_left;
60 61 62 63
} pyb_servo_obj_t;

STATIC pyb_servo_obj_t pyb_servo_obj[PYB_SERVO_NUM];

Damien George's avatar
Damien George committed
64
void servo_init(void) {
65
    timer_tim5_init();
66 67 68

    // reset servo objects
    for (int i = 0; i < PYB_SERVO_NUM; i++) {
69
        pyb_servo_obj[i].base.type = &pyb_servo_type;
70 71 72 73 74 75
        pyb_servo_obj[i].pulse_min = 64;
        pyb_servo_obj[i].pulse_max = 242;
        pyb_servo_obj[i].pulse_centre = 150;
        pyb_servo_obj[i].pulse_angle_90 = 97;
        pyb_servo_obj[i].pulse_speed_100 = 70;
        pyb_servo_obj[i].pulse_cur = 150;
76
        pyb_servo_obj[i].pulse_dest = 0;
77
        pyb_servo_obj[i].time_left = 0;
78
    }
79 80 81 82 83 84 85 86 87 88 89 90 91

    // assign servo objects to specific pins (must be some permutation of PA0-PA3)
    #ifdef pyb_pin_X1
    pyb_servo_obj[0].pin = &pyb_pin_X1;
    pyb_servo_obj[1].pin = &pyb_pin_X2;
    pyb_servo_obj[2].pin = &pyb_pin_X3;
    pyb_servo_obj[3].pin = &pyb_pin_X4;
    #else
    pyb_servo_obj[0].pin = &pin_A0;
    pyb_servo_obj[1].pin = &pin_A1;
    pyb_servo_obj[2].pin = &pin_A2;
    pyb_servo_obj[3].pin = &pin_A3;
    #endif
92 93 94 95 96 97 98
}

void servo_timer_irq_callback(void) {
    bool need_it = false;
    for (int i = 0; i < PYB_SERVO_NUM; i++) {
        pyb_servo_obj_t *s = &pyb_servo_obj[i];
        if (s->pulse_cur != s->pulse_dest) {
99 100 101 102 103 104 105
            // clamp pulse to within min/max
            if (s->pulse_dest < s->pulse_min) {
                s->pulse_dest = s->pulse_min;
            } else if (s->pulse_dest > s->pulse_max) {
                s->pulse_dest = s->pulse_max;
            }
            // adjust cur to get closer to dest
106 107 108 109 110 111 112 113 114 115
            if (s->time_left <= 1) {
                s->pulse_cur = s->pulse_dest;
                s->time_left = 0;
            } else {
                s->pulse_accum += s->pulse_dest - s->pulse_cur;
                s->pulse_cur += s->pulse_accum / s->time_left;
                s->pulse_accum %= s->time_left;
                s->time_left--;
                need_it = true;
            }
116
            // set the pulse width
117
            *(&TIM5->CCR1 + s->pin->pin) = s->pulse_cur;
118 119 120
        }
    }
    if (need_it) {
121
        __HAL_TIM_ENABLE_IT(&TIM5_Handle, TIM_IT_UPDATE);
122
    } else {
123
        __HAL_TIM_DISABLE_IT(&TIM5_Handle, TIM_IT_UPDATE);
124
    }
Damien George's avatar
Damien George committed
125 126
}

127
STATIC void servo_init_channel(pyb_servo_obj_t *s) {
128 129 130
    static const uint8_t channel_table[4] =
        {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4};
    uint32_t channel = channel_table[s->pin->pin];
Damien George's avatar
Damien George committed
131 132

    // GPIO configuration
133
    mp_hal_pin_config(s->pin, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, GPIO_AF2_TIM5);
Damien George's avatar
Damien George committed
134 135 136 137

    // PWM mode configuration
    TIM_OC_InitTypeDef oc_init;
    oc_init.OCMode = TIM_OCMODE_PWM1;
138
    oc_init.Pulse = s->pulse_cur; // units of 10us
Damien George's avatar
Damien George committed
139 140
    oc_init.OCPolarity = TIM_OCPOLARITY_HIGH;
    oc_init.OCFastMode = TIM_OCFAST_DISABLE;
141
    HAL_TIM_PWM_ConfigChannel(&TIM5_Handle, &oc_init, channel);
Damien George's avatar
Damien George committed
142 143

    // start PWM
144
    HAL_TIM_PWM_Start(&TIM5_Handle, channel);
Damien George's avatar
Damien George committed
145 146 147 148 149 150 151 152 153 154 155
}

/******************************************************************************/
// Micro Python bindings

STATIC mp_obj_t pyb_servo_set(mp_obj_t port, mp_obj_t value) {
    int p = mp_obj_get_int(port);
    int v = mp_obj_get_int(value);
    if (v < 50) { v = 50; }
    if (v > 250) { v = 250; }
    switch (p) {
156 157 158 159
        case 1: TIM5->CCR1 = v; break;
        case 2: TIM5->CCR2 = v; break;
        case 3: TIM5->CCR3 = v; break;
        case 4: TIM5->CCR4 = v; break;
Damien George's avatar
Damien George committed
160 161 162 163 164 165 166 167 168
    }
    return mp_const_none;
}

MP_DEFINE_CONST_FUN_OBJ_2(pyb_servo_set_obj, pyb_servo_set);

STATIC mp_obj_t pyb_pwm_set(mp_obj_t period, mp_obj_t pulse) {
    int pe = mp_obj_get_int(period);
    int pu = mp_obj_get_int(pulse);
169 170
    TIM5->ARR = pe;
    TIM5->CCR3 = pu;
Damien George's avatar
Damien George committed
171 172 173 174 175
    return mp_const_none;
}

MP_DEFINE_CONST_FUN_OBJ_2(pyb_pwm_set_obj, pyb_pwm_set);

176
STATIC void pyb_servo_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George's avatar
Damien George committed
177
    pyb_servo_obj_t *self = self_in;
178
    mp_printf(print, "<Servo %lu at %luus>", self - &pyb_servo_obj[0] + 1, 10 * self->pulse_cur);
Damien George's avatar
Damien George committed
179 180
}

181 182
/// \classmethod \constructor(id)
/// Create a servo object.  `id` is 1-4.
183
STATIC mp_obj_t pyb_servo_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
184
    // check arguments
Damien George's avatar
Damien George committed
185
    mp_arg_check_num(n_args, n_kw, 1, 1, false);
186 187

    // get servo number
188
    mp_int_t servo_id = mp_obj_get_int(args[0]) - 1;
189 190 191

    // check servo number
    if (!(0 <= servo_id && servo_id < PYB_SERVO_NUM)) {
192
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Servo(%d) doesn't exist", servo_id + 1));
193 194 195 196 197 198 199 200 201 202 203
    }

    // get and init servo object
    pyb_servo_obj_t *s = &pyb_servo_obj[servo_id];
    s->pulse_dest = s->pulse_cur;
    s->time_left = 0;
    servo_init_channel(s);

    return s;
}

204 205
/// \method pulse_width([value])
/// Get or set the pulse width in milliseconds.
206
STATIC mp_obj_t pyb_servo_pulse_width(mp_uint_t n_args, const mp_obj_t *args) {
207 208 209 210 211 212 213 214 215 216 217 218 219 220
    pyb_servo_obj_t *self = args[0];
    if (n_args == 1) {
        // get pulse width, in us
        return mp_obj_new_int(10 * self->pulse_cur);
    } else {
        // set pulse width, in us
        self->pulse_dest = mp_obj_get_int(args[1]) / 10;
        self->time_left = 0;
        servo_timer_irq_callback();
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_pulse_width_obj, 1, 2, pyb_servo_pulse_width);

221 222
/// \method calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]])
/// Get or set the calibration of the servo timing.
223
// TODO should accept 1 arg, a 5-tuple of values to set
224
STATIC mp_obj_t pyb_servo_calibration(mp_uint_t n_args, const mp_obj_t *args) {
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    pyb_servo_obj_t *self = args[0];
    if (n_args == 1) {
        // get calibration values
        mp_obj_t tuple[5];
        tuple[0] = mp_obj_new_int(10 * self->pulse_min);
        tuple[1] = mp_obj_new_int(10 * self->pulse_max);
        tuple[2] = mp_obj_new_int(10 * self->pulse_centre);
        tuple[3] = mp_obj_new_int(10 * (self->pulse_angle_90 + self->pulse_centre));
        tuple[4] = mp_obj_new_int(10 * (self->pulse_speed_100 + self->pulse_centre));
        return mp_obj_new_tuple(5, tuple);
    } else if (n_args >= 4) {
        // set min, max, centre
        self->pulse_min = mp_obj_get_int(args[1]) / 10;
        self->pulse_max = mp_obj_get_int(args[2]) / 10;
        self->pulse_centre = mp_obj_get_int(args[3]) / 10;
        if (n_args == 4) {
            return mp_const_none;
        } else if (n_args == 6) {
            self->pulse_angle_90 = mp_obj_get_int(args[4]) / 10 - self->pulse_centre;
            self->pulse_speed_100 = mp_obj_get_int(args[5]) / 10 - self->pulse_centre;
            return mp_const_none;
        }
    }

    // bad number of arguments
250
    nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "calibration expecting 1, 4 or 6 arguments, got %d", n_args));
251
}
252
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_calibration_obj, 1, 6, pyb_servo_calibration);
253

254 255 256 257 258
/// \method angle([angle, time=0])
/// Get or set the angle of the servo.
///
///   - `angle` is the angle to move to in degrees.
///   - `time` is the number of milliseconds to take to get to the specified angle.
259
STATIC mp_obj_t pyb_servo_angle(mp_uint_t n_args, const mp_obj_t *args) {
260 261 262
    pyb_servo_obj_t *self = args[0];
    if (n_args == 1) {
        // get angle
263
        return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 90 / self->pulse_angle_90);
264
    } else {
265
#if MICROPY_PY_BUILTINS_FLOAT
266
        self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_float(args[1]) / 90.0;
Damien George's avatar
Damien George committed
267
#else
268
        self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_int(args[1]) / 90;
Damien George's avatar
Damien George committed
269
#endif
270 271 272 273 274 275 276 277 278 279
        if (n_args == 2) {
            // set angle immediately
            self->time_left = 0;
        } else {
            // set angle over a given time (given in milli seconds)
            self->time_left = mp_obj_get_int(args[2]) / 20;
            self->pulse_accum = 0;
        }
        servo_timer_irq_callback();
        return mp_const_none;
Damien George's avatar
Damien George committed
280 281
    }
}
282
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_angle_obj, 1, 3, pyb_servo_angle);
Damien George's avatar
Damien George committed
283

284 285 286 287 288
/// \method speed([speed, time=0])
/// Get or set the speed of a continuous rotation servo.
///
///   - `speed` is the speed to move to change to, between -100 and 100.
///   - `time` is the number of milliseconds to take to get to the specified speed.
289
STATIC mp_obj_t pyb_servo_speed(mp_uint_t n_args, const mp_obj_t *args) {
290 291 292 293 294
    pyb_servo_obj_t *self = args[0];
    if (n_args == 1) {
        // get speed
        return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 100 / self->pulse_speed_100);
    } else {
295
#if MICROPY_PY_BUILTINS_FLOAT
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_float(args[1]) / 100.0;
#else
        self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_int(args[1]) / 100;
#endif
        if (n_args == 2) {
            // set speed immediately
            self->time_left = 0;
        } else {
            // set speed over a given time (given in milli seconds)
            self->time_left = mp_obj_get_int(args[2]) / 20;
            self->pulse_accum = 0;
        }
        servo_timer_irq_callback();
        return mp_const_none;
    }
}

STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_speed_obj, 1, 3, pyb_servo_speed);

315 316 317 318 319
STATIC const mp_rom_map_elem_t pyb_servo_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_pulse_width), MP_ROM_PTR(&pyb_servo_pulse_width_obj) },
    { MP_ROM_QSTR(MP_QSTR_calibration), MP_ROM_PTR(&pyb_servo_calibration_obj) },
    { MP_ROM_QSTR(MP_QSTR_angle), MP_ROM_PTR(&pyb_servo_angle_obj) },
    { MP_ROM_QSTR(MP_QSTR_speed), MP_ROM_PTR(&pyb_servo_speed_obj) },
Damien George's avatar
Damien George committed
320 321
};

322 323
STATIC MP_DEFINE_CONST_DICT(pyb_servo_locals_dict, pyb_servo_locals_dict_table);

324
const mp_obj_type_t pyb_servo_type = {
Damien George's avatar
Damien George committed
325 326
    { &mp_type_type },
    .name = MP_QSTR_Servo,
327 328
    .print = pyb_servo_print,
    .make_new = pyb_servo_make_new,
329
    .locals_dict = (mp_obj_dict_t*)&pyb_servo_locals_dict,
Damien George's avatar
Damien George committed
330
};