Skip to content

Commit e4e52f5

Browse files
committed
stmhal: Allow DAC object to be initialised from a pin.
Eg: dac = DAC(Pin.board.X5)
1 parent e503512 commit e4e52f5

1 file changed

Lines changed: 20 additions & 3 deletions

File tree

stmhal/dac.c

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
#include "runtime.h"
4040
#include "timer.h"
4141
#include "dac.h"
42+
#include "pin.h"
43+
#include "genhdr/pins.h"
4244

4345
/// \moduleref pyb
4446
/// \class DAC - digital to analog conversion
@@ -107,18 +109,33 @@ typedef struct _pyb_dac_obj_t {
107109
// create the dac object
108110
// currently support either DAC1 on X5 (id = 1) or DAC2 on X6 (id = 2)
109111

110-
/// \classmethod \constructor(id)
112+
/// \classmethod \constructor(port)
111113
/// Construct a new DAC object.
112114
///
113-
/// `id` can be 1 or 2: DAC 1 is on pin X5 and DAC 2 is on pin X6.
115+
/// `port` can be a pin object, or an integer (1 or 2).
116+
/// DAC(1) is on pin X5 and DAC(2) is on pin X6.
114117
STATIC mp_obj_t pyb_dac_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
115118
// check arguments
116119
mp_arg_check_num(n_args, n_kw, 1, 1, false);
117120

121+
// get pin/channel to output on
122+
mp_int_t dac_id;
123+
if (MP_OBJ_IS_INT(args[0])) {
124+
dac_id = mp_obj_get_int(args[0]);
125+
} else {
126+
const pin_obj_t *pin = pin_find(args[0]);
127+
if (pin == &pin_A4) {
128+
dac_id = 1;
129+
} else if (pin == &pin_A5) {
130+
dac_id = 2;
131+
} else {
132+
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin %s does not have DAC capabilities", qstr_str(pin->name)));
133+
}
134+
}
135+
118136
pyb_dac_obj_t *dac = m_new_obj(pyb_dac_obj_t);
119137
dac->base.type = &pyb_dac_type;
120138

121-
mp_int_t dac_id = mp_obj_get_int(args[0]);
122139
uint32_t pin;
123140
if (dac_id == 1) {
124141
pin = GPIO_PIN_4;

0 commit comments

Comments
 (0)