Go Down

### Topic: Something I didn't realise you could do (Read 637 times)previous topic - next topic

#### PORTB

##### Jan 22, 2018, 12:33 amLast Edit: Jan 22, 2018, 12:40 am by PORTB
For some reason it took me this long to figure out that you can use a function's return value to access a pin. May not be useful but nice to know (unless you already knew).

Code: [Select]
`#include <Streaming.h> //https://github.com/kachok/arduino-libraries/blob/master/Streaming/Streaming.h //Allows you to print to a stream using '<<'#define LED_PIN 33void setup(){ Serial.begin(115200); pinMode(LED_PIN, OUTPUT);}byte pinFunc(byte getPin){ Serial << "Pin " << getPin << " is "; return getPin;}bool pinState(){ static bool state = HIGH; state = !state; Serial << state << endl; return state;}void loop(){ digitalWrite(pinFunc(LED_PIN), pinState()); delay(1000);}`

#### flounder

#1
##### Feb 05, 2018, 01:51 pm
Just to be clear; the argument of any function is a computation that produces the result you want for that parameter.  The simplest computation is a constant, e.g., 1.  But anything that produces a suitable value may be used.  Since digitalWrite wants an 8-bit unsigned pin number, any computation you can imagine that produces an 8-bit value in the range of pin numbers is valid.

digitalWrite(SomePin - 1, (on ? HIGH : LOW) );

(yes, you might question why you know that SomePin, which might be a variable, requires subtracting 1 to get the correct pin number.  This would actually be a pretty poor programming style.  I use it to illustrate that any expression can be used, as long as it makes sense in your circuit).
joe

Go Up