|
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, (, ))}; |
@@ -238,6 +251,7 @@ int digitalPinToPinIndex(pin_size_t pinNumber) { |
238 | 251 | void pinMode(pin_size_t pinNumber, PinMode pinMode) { |
239 | 252 | RETURN_ON_INVALID_PIN(pinNumber); |
240 | 253 |
|
| 254 | + _reinit_peripheral_if_needed(pinNumber, NULL); |
241 | 255 | if (pinMode == INPUT) { // input mode |
242 | 256 | gpio_pin_configure_dt(&arduino_pins[pinNumber], GPIO_INPUT | GPIO_ACTIVE_HIGH); |
243 | 257 | } else if (pinMode == INPUT_PULLUP) { // input with internal pull-up |
@@ -478,6 +492,7 @@ void analogWrite(pin_size_t pinNumber, int value) { |
478 | 492 | return; |
479 | 493 | } |
480 | 494 |
|
| 495 | + _reinit_peripheral_if_needed(pinNumber, arduino_pwm[idx].dev); |
481 | 496 | value = CLAMP(value, 0, maxInput); |
482 | 497 |
|
483 | 498 | const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period); |
@@ -506,6 +521,9 @@ void analogWrite(enum dacPins dacName, int value) { |
506 | 521 | return; |
507 | 522 | } |
508 | 523 |
|
| 524 | + // TODO: add reverse map to find pin name from DAC* define |
| 525 | + // In the meantime, consider A0 == DAC0 |
| 526 | + _reinit_peripheral_if_needed((pin_size_t)(dacName + A0), dac_dev); |
509 | 527 | ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]); |
510 | 528 | if (ret != 0) { |
511 | 529 | return; |
@@ -568,6 +586,8 @@ int analogRead(pin_size_t pinNumber) { |
568 | 586 | return -ENOTSUP; |
569 | 587 | } |
570 | 588 |
|
| 589 | + _reinit_peripheral_if_needed(pinNumber, arduino_adc[idx].dev); |
| 590 | + |
571 | 591 | err = adc_channel_setup(arduino_adc[idx].dev, &arduino_adc[idx].channel_cfg); |
572 | 592 | if (err < 0) { |
573 | 593 | return err; |
|
0 commit comments