|
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, (, ))}; |
@@ -215,6 +228,7 @@ void yield(void) { |
215 | 228 | * A high physical level will be interpreted as value 1 |
216 | 229 | */ |
217 | 230 | void pinMode(pin_size_t pinNumber, PinMode pinMode) { |
| 231 | + _reinit_peripheral_if_needed(pinNumber, NULL); |
218 | 232 | if (pinMode == INPUT) { // input mode |
219 | 233 | gpio_pin_configure_dt(&arduino_pins[pinNumber], GPIO_INPUT | GPIO_ACTIVE_HIGH); |
220 | 234 | } else if (pinMode == INPUT_PULLUP) { // input with internal pull-up |
@@ -443,6 +457,7 @@ void analogWrite(pin_size_t pinNumber, int value) { |
443 | 457 | return; |
444 | 458 | } |
445 | 459 |
|
| 460 | + _reinit_peripheral_if_needed(pinNumber, arduino_pwm[idx].dev); |
446 | 461 | value = CLAMP(value, 0, maxInput); |
447 | 462 |
|
448 | 463 | const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period); |
@@ -471,6 +486,9 @@ void analogWrite(enum dacPins dacName, int value) { |
471 | 486 | return; |
472 | 487 | } |
473 | 488 |
|
| 489 | + // TODO: add reverse map to find pin name from DAC* define |
| 490 | + // In the meantime, consider A0 == DAC0 |
| 491 | + _reinit_peripheral_if_needed((pin_size_t)(dacName + A0), dac_dev); |
474 | 492 | ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]); |
475 | 493 | if (ret != 0) { |
476 | 494 | return; |
@@ -533,6 +551,8 @@ int analogRead(pin_size_t pinNumber) { |
533 | 551 | return -ENOTSUP; |
534 | 552 | } |
535 | 553 |
|
| 554 | + _reinit_peripheral_if_needed(pinNumber, arduino_adc[idx].dev); |
| 555 | + |
536 | 556 | err = adc_channel_setup(arduino_adc[idx].dev, &arduino_adc[idx].channel_cfg); |
537 | 557 | if (err < 0) { |
538 | 558 | return err; |
|
0 commit comments