servo.c 11.1 KB
Newer Older
Damien George's avatar
Damien George committed
1
2
3
4
#include <stdio.h>

#include "stm32f4xx_hal.h"

5
#include "nlr.h"
Damien George's avatar
Damien George committed
6
7
8
9
#include "misc.h"
#include "mpconfig.h"
#include "qstr.h"
#include "obj.h"
10
#include "runtime.h"
11
#include "timer.h"
Damien George's avatar
Damien George committed
12
13
#include "servo.h"

14
15
16
17
18
/// \moduleref pyb
/// \class Servo - 3-wire hobby servo driver
///
/// Servo controls standard hobby servos with 3-wires (ground, power, signal).

Damien George's avatar
Damien George committed
19
20
21
// this servo driver uses hardware PWM to drive servos on PA0, PA1, PA2, PA3 = X1, X2, X3, X4
// TIM2 and TIM5 have CH1, CH2, CH3, CH4 on PA0-PA3 respectively
// they are both 32-bit counters with 16-bit prescaler
22
// we use TIM5
Damien George's avatar
Damien George committed
23

24
25
26
27
#define PYB_SERVO_NUM (4)

typedef struct _pyb_servo_obj_t {
    mp_obj_base_t base;
28
29
30
31
32
33
34
35
    uint8_t servo_id;
    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
36
    int16_t pulse_accum;
37
    uint16_t time_left;
38
39
40
41
} pyb_servo_obj_t;

STATIC pyb_servo_obj_t pyb_servo_obj[PYB_SERVO_NUM];

Damien George's avatar
Damien George committed
42
void servo_init(void) {
43
    timer_tim5_init();
44
45
46

    // reset servo objects
    for (int i = 0; i < PYB_SERVO_NUM; i++) {
47
        pyb_servo_obj[i].base.type = &pyb_servo_type;
48
        pyb_servo_obj[i].servo_id = i + 1;
49
50
51
52
53
54
        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;
55
        pyb_servo_obj[i].pulse_dest = 0;
56
        pyb_servo_obj[i].time_left = 0;
57
58
59
60
61
62
63
64
    }
}

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) {
65
66
67
68
69
70
71
            // 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
72
73
74
75
76
77
78
79
80
81
            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;
            }
82
            // set the pulse width
83
            switch (s->servo_id) {
84
85
86
87
                case 1: TIM5->CCR1 = s->pulse_cur; break;
                case 2: TIM5->CCR2 = s->pulse_cur; break;
                case 3: TIM5->CCR3 = s->pulse_cur; break;
                case 4: TIM5->CCR4 = s->pulse_cur; break;
88
89
90
91
            }
        }
    }
    if (need_it) {
92
        __HAL_TIM_ENABLE_IT(&TIM5_Handle, TIM_IT_UPDATE);
93
    } else {
94
        __HAL_TIM_DISABLE_IT(&TIM5_Handle, TIM_IT_UPDATE);
95
    }
Damien George's avatar
Damien George committed
96
97
}

98
STATIC void servo_init_channel(pyb_servo_obj_t *s) {
Damien George's avatar
Damien George committed
99
100
    uint32_t pin;
    uint32_t channel;
101
    switch (s->servo_id) {
Damien George's avatar
Damien George committed
102
103
104
105
106
107
108
109
110
111
112
113
114
        case 1: pin = GPIO_PIN_0; channel = TIM_CHANNEL_1; break;
        case 2: pin = GPIO_PIN_1; channel = TIM_CHANNEL_2; break;
        case 3: pin = GPIO_PIN_2; channel = TIM_CHANNEL_3; break;
        case 4: pin = GPIO_PIN_3; channel = TIM_CHANNEL_4; break;
        default: return;
    }

    // GPIO configuration
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.Pin = pin;
    GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStructure.Speed = GPIO_SPEED_FAST;
    GPIO_InitStructure.Pull = GPIO_NOPULL;
115
    GPIO_InitStructure.Alternate = GPIO_AF2_TIM5;
Damien George's avatar
Damien George committed
116
117
118
119
120
    HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);

    // PWM mode configuration
    TIM_OC_InitTypeDef oc_init;
    oc_init.OCMode = TIM_OCMODE_PWM1;
121
    oc_init.Pulse = s->pulse_cur; // units of 10us
Damien George's avatar
Damien George committed
122
123
    oc_init.OCPolarity = TIM_OCPOLARITY_HIGH;
    oc_init.OCFastMode = TIM_OCFAST_DISABLE;
124
    HAL_TIM_PWM_ConfigChannel(&TIM5_Handle, &oc_init, channel);
Damien George's avatar
Damien George committed
125
126

    // start PWM
127
    HAL_TIM_PWM_Start(&TIM5_Handle, channel);
Damien George's avatar
Damien George committed
128
129
130
131
132
133
134
135
136
137
138
}

/******************************************************************************/
// 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) {
139
140
141
142
        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
143
144
145
146
147
148
149
150
151
    }
    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);
152
153
    TIM5->ARR = pe;
    TIM5->CCR3 = pu;
Damien George's avatar
Damien George committed
154
155
156
157
158
    return mp_const_none;
}

MP_DEFINE_CONST_FUN_OBJ_2(pyb_pwm_set_obj, pyb_pwm_set);

159
STATIC void pyb_servo_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George's avatar
Damien George committed
160
    pyb_servo_obj_t *self = self_in;
161
    print(env, "<Servo %lu at %luus>", self->servo_id, 10 * self->pulse_cur);
Damien George's avatar
Damien George committed
162
163
}

164
165
/// \classmethod \constructor(id)
/// Create a servo object.  `id` is 1-4.
166
167
STATIC mp_obj_t pyb_servo_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
    // check arguments
Damien George's avatar
Damien George committed
168
    mp_arg_check_num(n_args, n_kw, 1, 1, false);
169
170
171
172
173
174

    // get servo number
    machine_int_t servo_id = mp_obj_get_int(args[0]) - 1;

    // check servo number
    if (!(0 <= servo_id && servo_id < PYB_SERVO_NUM)) {
175
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Servo %d does not exist", servo_id + 1));
176
177
178
179
180
181
182
183
184
185
186
    }

    // 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;
}

187
188
/// \method pulse_width([value])
/// Get or set the pulse width in milliseconds.
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
STATIC mp_obj_t pyb_servo_pulse_width(uint n_args, const mp_obj_t *args) {
    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);

204
205
/// \method calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]])
/// Get or set the calibration of the servo timing.
206
STATIC mp_obj_t pyb_servo_calibration(uint n_args, const mp_obj_t *args) {
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    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
232
    nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "calibration expecting 1, 4 or 6 arguments, got %d", n_args));
233
}
234
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_calibration_obj, 1, 6, pyb_servo_calibration);
235

236
237
238
239
240
/// \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.
241
STATIC mp_obj_t pyb_servo_angle(uint n_args, const mp_obj_t *args) {
242
243
244
    pyb_servo_obj_t *self = args[0];
    if (n_args == 1) {
        // get angle
245
        return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 90 / self->pulse_angle_90);
246
    } else {
Damien George's avatar
Damien George committed
247
#if MICROPY_ENABLE_FLOAT
248
        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
249
#else
250
        self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_int(args[1]) / 90;
Damien George's avatar
Damien George committed
251
#endif
252
253
254
255
256
257
258
259
260
261
        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
262
263
    }
}
264
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_angle_obj, 1, 3, pyb_servo_angle);
Damien George's avatar
Damien George committed
265

266
267
268
269
270
/// \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.
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
STATIC mp_obj_t pyb_servo_speed(uint n_args, const mp_obj_t *args) {
    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 {
#if MICROPY_ENABLE_FLOAT
        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);

297
STATIC const mp_map_elem_t pyb_servo_locals_dict_table[] = {
298
    { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width), (mp_obj_t)&pyb_servo_pulse_width_obj },
299
    { MP_OBJ_NEW_QSTR(MP_QSTR_calibration), (mp_obj_t)&pyb_servo_calibration_obj },
300
    { MP_OBJ_NEW_QSTR(MP_QSTR_angle), (mp_obj_t)&pyb_servo_angle_obj },
301
    { MP_OBJ_NEW_QSTR(MP_QSTR_speed), (mp_obj_t)&pyb_servo_speed_obj },
Damien George's avatar
Damien George committed
302
303
};

304
305
STATIC MP_DEFINE_CONST_DICT(pyb_servo_locals_dict, pyb_servo_locals_dict_table);

306
const mp_obj_type_t pyb_servo_type = {
Damien George's avatar
Damien George committed
307
308
    { &mp_type_type },
    .name = MP_QSTR_Servo,
309
310
    .print = pyb_servo_print,
    .make_new = pyb_servo_make_new,
311
    .locals_dict = (mp_obj_t)&pyb_servo_locals_dict,
Damien George's avatar
Damien George committed
312
};