Hi. This is Albert and Angelica. Here is the code for making an LED blink the Fibonacci Sequence. No fancy code or mathematical equations for this one. It basically treats the first Fibonacci number as if it were the beginning of a fencepost problem and solves it as a single unique case. It's true that performing the if/else check every single time the void loop is run seems to be redundant, but in reality, a single conditional statement test should have a negligible effect on the time complexity of the entire program. Variables are used to remember what values are in the n-1 and n-2 spots of the sequence and updated after blinking the LED.
/*
A simple program that blinks an LED a number of times in accordance with the Fibonacci Sequence (1, 1, 2, 3, 5, 8, 13, 21 . . .)
There are 3 second delays between each Fibonacci number.
*/
int led = 13;
int nMinus1 = 0; // keeps track of the previous number
int nMinus2 = 0; // keeps track of the number before the previous
int blinks = 0; // number of times to blink the LED
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
// Takes care of the first case like a classic fencepost problem
if (nMinus1 == 0) {
digitalWrite(led, HIGH);
delay(200);
digitalWrite(led, LOW);
delay(200);
nMinus1 = 1;
} else {
blinks = nMinus1 + nMinus2;
for (int x = 0; x < blinks; x++) {
digitalWrite(led, HIGH);
delay(300);
digitalWrite(led, LOW);
delay(300);
}
nMinus2 = nMinus1;
nMinus1 = blinks;
}
delay(3000);
}
No comments:
Post a Comment