usrsw.c 1.84 KB
Newer Older
Dave Hylands's avatar
Dave Hylands committed
1
2
#include <stdio.h>
#include <stm32f4xx.h>
3
4
5

#include "misc.h"
#include "mpconfig.h"
6
#include "qstr.h"
7
#include "obj.h"
Dave Hylands's avatar
Dave Hylands committed
8
#include "runtime.h"
9
10
#include "usrsw.h"

Dave Hylands's avatar
Dave Hylands committed
11
12
13
14
#include "exti.h"
#include "gpio.h"
#include "pin.h"
#include "build/pins.h"
15

Dave Hylands's avatar
Dave Hylands committed
16
17
18
19
20
21
// Usage Model:
//
// pyb.switch() returns True if the user switch is pressed, False otherwise.
//
// pyb.switch(callback) will register a callback to be called when the user
//                      switch is pressed.
22
//
Dave Hylands's avatar
Dave Hylands committed
23
24
25
26
// pyb.switch(None) will remove the callback.
//
// Example:
//
27
// def switch_pressed():
Dave Hylands's avatar
Dave Hylands committed
28
29
//     print("User Switch pressed")
//
30
// pyb.switch(switch_pressed)
31

Dave Hylands's avatar
Dave Hylands committed
32
static mp_obj_t switch_user_callback_obj;
33

34
static mp_obj_t switch_callback(mp_obj_t line) {
Dave Hylands's avatar
Dave Hylands committed
35
36
37
38
39
    if (switch_user_callback_obj != mp_const_none) {
        rt_call_function_0(switch_user_callback_obj);
    }
    return mp_const_none;
}
40
static MP_DEFINE_CONST_FUN_OBJ_1(switch_callback_obj, switch_callback);
41

Dave Hylands's avatar
Dave Hylands committed
42
43
44
45
46
47
void switch_init(void) {
    switch_user_callback_obj = mp_const_none;
    exti_register((mp_obj_t)&USRSW_PIN,
                  MP_OBJ_NEW_SMALL_INT(EXTI_Mode_Interrupt),
                  MP_OBJ_NEW_SMALL_INT(USRSW_EXTI_EDGE),
                  (mp_obj_t)&switch_callback_obj,
48
                  NULL);
Dave Hylands's avatar
Dave Hylands committed
49
    pyb_gpio_input((mp_obj_t)&USRSW_PIN, MP_OBJ_NEW_SMALL_INT(USRSW_PUPD));
50
51
}

52
int switch_get(void) {
Dave Hylands's avatar
Dave Hylands committed
53
54
    int val = ((USRSW_PIN.gpio->IDR & USRSW_PIN.pin_mask) != 0);
    return val == USRSW_PRESSED;
55
56
57
58
59
}

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

Dave Hylands's avatar
Dave Hylands committed
60
61
62
static mp_obj_t pyb_switch(uint n_args, mp_obj_t *args) {
    if (n_args == 0) {
        return switch_get() ? mp_const_true : mp_const_false;
63
    }
Dave Hylands's avatar
Dave Hylands committed
64
65
    switch_user_callback_obj = args[0];
    return mp_const_none;
66
67
}

Dave Hylands's avatar
Dave Hylands committed
68
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_switch_obj, 0, 1, pyb_switch);