Source
Scott Fitzgerald and Michael Shiloh,
The Arduino Projects Book Chapter 2: Spaceship Interface
Contents
Arduino board pins and electronic components connected to them
Assign board pins input/output roles.
1
2
| int inputPins[] = {2};
int outputPins[] = {LED_BUILTIN, 3, 4, 5};
|
After connecting breadboard pushbutton and LEDs to Arduino board pins,
identify the pins here.
1
2
3
| int pushButton = 2;
int greenLED = 3;
int redLEDs[] = {4, 5};
|
Put breadboard LED pin states in an array for convenience.
1
| int ledStates[] = {HIGH, LOW};
|
Set starting state of breadboard pushbutton.
1
| int pushButtonState = LOW;
|
Helper functions
1
2
3
4
5
6
| void pulseLED(int pin, int delayTime) {
for (int state : ledStates) {
digitalWrite(pin, state);
delay(delayTime);
}
}
|
1
2
3
4
5
6
| void multiPulseLED(int pin, int pulses, int delayTime) {
for (int i = 0; i < pulses; i++) {
pulseLED(pin, delayTime);
delay(delayTime);
}
}
|
On button down, green LED off and alternately pulse red LEDS.
On button up, green LED on and red LEDs off.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| void handlepushButtonState() {
pushButtonState = digitalRead(pushButton);
if (pushButtonState == HIGH) { // button down
digitalWrite(greenLED, LOW);
for (int led : redLEDs) {
multiPulseLED(led, 2, 25); // fast double pulse
}
} else { // button up
digitalWrite(greenLED, HIGH);
for (int led : redLEDs) {
digitalWrite(led, LOW);
}
}
}
|
setup()
and loop()
1
2
3
4
5
6
7
8
9
| void setup() {
for (int pin : inputPins) pinMode(pin, INPUT);
for (int pin : outputPins) pinMode(pin, OUTPUT);
digitalWrite(greenLED, HIGH); // green LED on
}
void loop() {
handlepushButtonState();
}
|