Making Furniture Interactive

September 28, 2007

Example of subroutines in Arduino

Filed under: Course Materials,Examples — jet @ 3:42 pm

A simple example of an Arduino sketch that uses subroutines.

/* subroutine_demo.

The basics of subroutines in Arduino, this is no substitute for the
real documentation.
*/

int minReadPin = 1;                // the first pin we're reading
int maxReadPin = 8;                // the highest pin we're reading

int minLedPin = 9;
int maxLedPin = 11;
int redLedPin = 9;
int blueLedPin = 10;
int greenLedPin = 11;

void setup() {                    // run once, when the sketch starts
pinMode(redLedPin, OUTPUT);      // sets the digital pin as output
}

// a subroutine with no arguments
// turn all the LEDs off
void LedAllOff() {
digitalWrite(redLedPin, LOW);
digitalWrite(blueLedPin, LOW);
digitalWrite(greenLedPin, LOW);

}

// a subroutine with two arguments
void LedOn(int pin, int duration) {
digitalWrite(pin, HIGH);   // sets the LED on
delay(duration);                  // waits for a second
digitalWrite(pin, LOW);    // sets the LED off
}

// a subroutine that returns a value using a loop
bool AreAnyPinsTrue()  {

// start with minReadPin and go to maxReadPin, checking each pin
for (int i = minReadPin; i <= maxReadPin; i++) {
// make sure we're in read mode.
pinMode(i, INPUT);
int i = digitalRead(i);
if (i > 0) {
return true;
}

/* or we can be the cool c hacker:
if(digitalRead(i)) {
return true;
}
*/
}
// if we didn't find any pins on, then return false by default
return false;
}

void loop()                     // run over and over again
{
LedAllOff();
if (AreAnyPinsTrue() == true) {
LedOn(redLedPin, 1000);
}
}

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.