|
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 |
@@ -407,6 +421,7 @@ void analogWrite(pin_size_t pinNumber, int value) { |
407 | 421 | return; |
408 | 422 | } |
409 | 423 |
|
| 424 | + _reinit_peripheral_if_needed(pinNumber, arduino_pwm[idx].dev); |
410 | 425 | value = CLAMP(value, 0, maxInput); |
411 | 426 |
|
412 | 427 | const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period); |
@@ -435,6 +450,9 @@ void analogWrite(enum dacPins dacName, int value) { |
435 | 450 | return; |
436 | 451 | } |
437 | 452 |
|
| 453 | + // TODO: add reverse map to find pin name from DAC* define |
| 454 | + // In the meantime, consider A0 == DAC0 |
| 455 | + _reinit_peripheral_if_needed((pin_size_t)(dacName + A0), dac_dev); |
438 | 456 | ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]); |
439 | 457 | if (ret != 0) { |
440 | 458 | return; |
@@ -497,6 +515,8 @@ int analogRead(pin_size_t pinNumber) { |
497 | 515 | return -ENOTSUP; |
498 | 516 | } |
499 | 517 |
|
| 518 | + _reinit_peripheral_if_needed(pinNumber, arduino_adc[idx].dev); |
| 519 | + |
500 | 520 | err = adc_channel_setup(arduino_adc[idx].dev, &arduino_adc[idx].channel_cfg); |
501 | 521 | if (err < 0) { |
502 | 522 | return err; |
|
0 commit comments