Skip to content

Commit fd860dc

Browse files
committed
stmhal: Add .value() method to Switch object, to mirror Pin and Signal.
1 parent 4abe373 commit fd860dc

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

docs/library/pyb.Switch.rst

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ A Switch object is used to control a push-button switch.
88
Usage::
99

1010
sw = pyb.Switch() # create a switch object
11-
sw() # get state (True if pressed, False otherwise)
11+
sw.value() # get state (True if pressed, False otherwise)
12+
sw() # shorthand notation to get the switch state
1213
sw.callback(f) # register a callback to be called when the
1314
# switch is pressed down
1415
sw.callback(None) # remove the callback
@@ -34,6 +35,10 @@ Methods
3435
Call switch object directly to get its state: ``True`` if pressed down,
3536
``False`` otherwise.
3637

38+
.. method:: Switch.value()
39+
40+
Get the switch state. Returns `True` if pressed down, otherwise `False`.
41+
3742
.. method:: Switch.callback(fun)
3843

3944
Register the given function to be called when the switch is pressed down.

docs/pyboard/tutorial/switch.rst

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,18 @@ the name ``pyb`` does not exist.
1515

1616
With the switch object you can get its status::
1717

18-
>>> sw()
18+
>>> sw.value()
1919
False
2020

2121
This will print ``False`` if the switch is not held, or ``True`` if it is held.
2222
Try holding the USR switch down while running the above command.
2323

24+
There is also a shorthand notation to get the switch status, by "calling" the
25+
switch object::
26+
27+
>>> sw()
28+
False
29+
2430
Switch callbacks
2531
----------------
2632

stmhal/usrsw.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,12 @@ mp_obj_t pyb_switch_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_
9797
return switch_get() ? mp_const_true : mp_const_false;
9898
}
9999

100+
mp_obj_t pyb_switch_value(mp_obj_t self_in) {
101+
(void)self_in;
102+
return mp_obj_new_bool(switch_get());
103+
}
104+
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_switch_value_obj, pyb_switch_value);
105+
100106
STATIC mp_obj_t switch_callback(mp_obj_t line) {
101107
if (MP_STATE_PORT(pyb_switch_callback) != mp_const_none) {
102108
mp_call_function_0(MP_STATE_PORT(pyb_switch_callback));
@@ -123,6 +129,7 @@ mp_obj_t pyb_switch_callback(mp_obj_t self_in, mp_obj_t callback) {
123129
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_switch_callback_obj, pyb_switch_callback);
124130

125131
STATIC const mp_rom_map_elem_t pyb_switch_locals_dict_table[] = {
132+
{ MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&pyb_switch_value_obj) },
126133
{ MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_switch_callback_obj) },
127134
};
128135

0 commit comments

Comments
 (0)