|
9 | 9 |
|
10 | 10 | #include <zephyr/spinlock.h> |
11 | 11 |
|
| 12 | +// create an array of arduino_pins with functions to reinitialize pins if needed |
| 13 | +static const struct device *pinmux_array[DT_PROP_LEN(DT_PATH(zephyr_user), digital_pin_gpios)] = { |
| 14 | + nullptr}; |
| 15 | + |
| 16 | +void _reinit_peripheral_if_needed(pin_size_t pin, const struct device *dev) { |
| 17 | + if (pinmux_array[pin] != dev) { |
| 18 | + pinmux_array[pin] = dev; |
| 19 | + if (dev != NULL) { |
| 20 | + dev->ops.init(dev); |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
12 | 25 | static const struct gpio_dt_spec arduino_pins[] = { |
13 | 26 | DT_FOREACH_PROP_ELEM_SEP( |
14 | 27 | DT_PATH(zephyr_user), digital_pin_gpios, GPIO_DT_SPEC_GET_BY_IDX, (, ))}; |
@@ -226,6 +239,7 @@ void yield(void) { |
226 | 239 | void pinMode(pin_size_t pinNumber, PinMode pinMode) { |
227 | 240 | RETURN_ON_INVALID_PIN(pinNumber); |
228 | 241 |
|
| 242 | + _reinit_peripheral_if_needed(pinNumber, NULL); |
229 | 243 | if (pinMode == INPUT) { // input mode |
230 | 244 | gpio_pin_configure_dt(&arduino_pins[pinNumber], GPIO_INPUT | GPIO_ACTIVE_HIGH); |
231 | 245 | } else if (pinMode == INPUT_PULLUP) { // input with internal pull-up |
@@ -466,6 +480,7 @@ void analogWrite(pin_size_t pinNumber, int value) { |
466 | 480 | return; |
467 | 481 | } |
468 | 482 |
|
| 483 | + _reinit_peripheral_if_needed(pinNumber, arduino_pwm[idx].dev); |
469 | 484 | value = CLAMP(value, 0, maxInput); |
470 | 485 |
|
471 | 486 | const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period); |
@@ -494,6 +509,9 @@ void analogWrite(enum dacPins dacName, int value) { |
494 | 509 | return; |
495 | 510 | } |
496 | 511 |
|
| 512 | + // TODO: add reverse map to find pin name from DAC* define |
| 513 | + // In the meantime, consider A0 == DAC0 |
| 514 | + _reinit_peripheral_if_needed((pin_size_t)(dacName + A0), dac_dev); |
497 | 515 | ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]); |
498 | 516 | if (ret != 0) { |
499 | 517 | return; |
@@ -556,6 +574,8 @@ int analogRead(pin_size_t pinNumber) { |
556 | 574 | return -ENOTSUP; |
557 | 575 | } |
558 | 576 |
|
| 577 | + _reinit_peripheral_if_needed(pinNumber, arduino_adc[idx].dev); |
| 578 | + |
559 | 579 | err = adc_channel_setup(arduino_adc[idx].dev, &arduino_adc[idx].channel_cfg); |
560 | 580 | if (err < 0) { |
561 | 581 | return err; |
|
0 commit comments