Is it possible to change pinmodes within the loop?
I am using some analogue pins with attachInterrupts, which I have declared in the setup() part.
I want to use some of those pins also for measuring an analogue value, but not at the same instance.
For this purpose I want to change the the pinmode within the loop, detach the interrupt for the time being, do the measurement. After that I want to change back the pinmode and re-attach the interrupt.
Is this possible within a loop?
Yes, that is possible. In fact
analogRead() implicitly changes the pin mode anyway - so no need to change pin mode.
BTW, between which pin modes would you be switching?
That would be some info quite important in order to answer you question (if there wasn’t the implicit switching already).
Thanks for the quick response ScruffR!
The pins for which I will apply mode-switching are A0, A2, A3 and A4
Which modes would you be switching back and forth?
I reconsidered the entire design once again. I will use A0, A2, A3 and A4 for two different input-purposes:
1.I will attach interrupts to all four, but I will also
2. use them as real analogue inputs.
However, in the code I can make sure that both functions will never coincide: I intend to “isolate” the latter part by putting that part of the code between noInterrupts() and interrupts(), with the part dealing with analogread() between them
In the setup I will specify the pinmode() for these pins and there I will also specify the attachInterrupt()s.
Is that the correct way or will these specifications interfere with the analogRead() in the loop?
If so, what would be the correct way to deal with this?
Some time in the past the behaviour of
analogRead() must have changed to only store the pevious pin mode and leaving the recalling of that state to an eventual call of
This seems to be impacting your case, but you still have not told us which mode you need for your interrupts - despite being asked at least twice.
INPUT_PULLDOWN or even
It depends how long you'd be planning to make your
For a single read, that should be good, but if you intended to do some averaging or other treatment that may take more than just a microseconds (up to a few milliseconds). If it may take any longer I'd
attachInterrupt() again when done.
I'd think the sweet spot between the two would be about 5-10 times the overhead of the latter approach should be where you may want to consider transitioning.
You could also do some tests yourself what works best and maybe gives you the best performance.
e.g. what is faster reverting to the original pin mode: explicitly calling
pinMode() or letting a dummy
digitalRead() do it implicitly or if you'd have a
digitalRead() in your normal logic, just let it do the job then.
I do appologise for not informing you on the mode for the interrupts; I thought I has done that already, but I obviously didn’t.
Anyhow, for the inputs I will use INPUT_PULLDOWN