I always like to write my own little programs when i'm trying to understand how something works.
I have been trying to understand how we can send data from one function to the other, so i tried to create a little sketch with prints out the Fibonacci sequence. The numbers are calculated in one place and then sent to another function which will print them.
Here is the code i am using:
/*
Just a little simple sketch to try to understand how to send values
from one function to another.
...and maybe understand a little bit better te Fibonacci Sequence!
Circuit:
button to Arduino Pin4 (with pull-up resistor)
April 2014 Luis Pato
*/
// VARIABLES
const int button = 4; // button Pin
int buttonState; // will hold the current state of button
int lastButtonState = HIGH; // will store the previous state of button
unsigned long a = 1; // variables used to calculate the Fib. numbers
unsigned long b = 1;
unsigned long c;
void setup() {
pinMode(button,INPUT); // set button as input
Serial.begin(9600); // begin serial communication
delay(2000); // 2s delay, so we can start the Serial Monitor
intro(); // print the "intro info"
}
void loop() {
buttonState = digitalRead(button); // read the button state
// if button is just pressed
if(buttonState == LOW && buttonState != lastButtonState){
c = a + b; // calculate next Fib. number
printNumbers(a,b,c); // send F[n-2], F[n-1] and F[n] to the print function
a = b; // update F[n-2]
b = c; // update F[n-1]
}
lastButtonState = buttonState; // store last button state
}
void printNumbers(int d, int e, int f){
// this funcion is used to print the Fib. numbers into a "table" on the Serial Monitor
Serial.print(d); // print F[n-2]
Serial.print("\t");
Serial.print("+");
Serial.print("\t");
Serial.print(e); // print F[n-1]
Serial.print("\t");
Serial.print("=");
Serial.print("\t");
Serial.println(f); // print F[n], the new Fib. number
}
void intro() {
// this function prints some intro info about the Fibonacci Sequence
Serial.println("The Fibonacci Sequence works by adding a number to its preceding number in the sequence");
Serial.println(" ");
Serial.print("F[n-2]");
Serial.print("\t");
Serial.print("\t");
Serial.print("F[n-1]");
Serial.print("\t");
Serial.print("\t");
Serial.print("F[n]");
Serial.println();
for (int i=0; i<5; i++){ // print the first 5 numbers in the sequence
delay(250);
c = a + b;
printNumbers(a,b,c);
a = b;
b = c;
}
Serial.println(" ");
Serial.println("Click the button to find out the next number in the sequence...");
Serial.println(" ");
}
and here is the output:
but, as you can see, when we get to the:
17711 + 28657 =
instead of getting 46368 we get -19168
why is this happening?
Is it something wrong with my "formula"? are the values rolling over? Is Mr. Fibonacci playing a joke on me?
![]()