Arduino Functions with Variable DigitalWrite

01 Dec

I feel like I’ve been looking for a couple of years for this solution and could never find it. Well I worked it out for myself so I thought I should post it so the answer can be found for others as it really does seem to be complete undocumented online.

int redLed = 13; // assigning redLed with the onboard LED
int blueLed = 12; // assigning blueLed with offboard LED with resister

void setup(){
pinMode(redLed , OUTPUT); // set these pin as outputs for digital writes
pinMode(blueLed , OUTPUT); // set these pin as outputs for digital writes

void loop(){
ledBlinking(redLed, 6, 500, 100); // run function targeting the red LED
ledBlinking(blueLed, 12, 100, 100); // run function targeting the blue LED

void ledBlinking(word led, int amount, int timeOn, int timeOff){ // set the variables used between loop and function
for ( int i=1; i<=amount; i=i+1 ) { // for each i in amount run the below digitalWrite(led, HIGH); // bring the chosen pin high delay(timeOn); // wait the LED time on digitalWrite(led, LOW); // bring the chosen pin low delay(timeOff); // wait the LED time off } // loop back to i counter until over }

So hopefully you see what I'm doing here. I'm telling the function in void loop to use the pin redLed and blueLed with a word (not a string) variable. The rest are simple integers holding the amount of flashes, and how long to hold them on and off for.

Simple when you know how, now on to the bigger project.


Tags: , , , , , ,

Leave a Reply