こうなると、スケッチの信号点灯処理の繰り返し部分が気になって来る。ソフト経験のある方なら関数化したくなるのが人情と言うものだろう。
というわけで、signalSwitch() という関数を新たに設け、各信号の値をそこへ渡す形に改造したのが以下である。
[ スケッチ:IfStatementConditional31]
// These constants won't change:
const int analogPin = A0; // pin that the sensor is attached to
const int ledPin = 13; // pin that the LED is attached to
const int led2Pin = 12; // pin that the LED is attached to
const int led3Pin = 11; // pin that the LED is attached to
const int threshold = 150; // an arbitrary threshold level that's in the range of the analog input
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
pinMode(led2Pin, OUTPUT);
pinMode(led3Pin, OUTPUT);
// initialize serial communications:
Serial.begin(9600);
}
void loop() {
// read the value of the potentiometer:
int analogValue = analogRead(analogPin);
// if the analog value is high enough, turn on the LED:
if (analogValue < threshold) {
signalSwitch(1, 0, 0); // RED
delay(6000);
signalSwitch(0, 0, 1); // YEL
delay(6000);
} else {
signalSwitch(0, 1, 0); // GRN
}
// print the analog value:
Serial.println(analogValue);
delay(1); // delay in between reads for stability
}
void signalSwitch(int x, int y, int z) {
digitalWrite(ledPin, x);
digitalWrite(led2Pin, y);
digitalWrite(led3Pin, z);
return;
}