Fibonacci sequence program

Hi, I have been struggling with an assignment to program my Arduino board to do the Fibonacci sequence in class. the assignment goes as follows:

Program the Arduino board to output the Fibonacci sequence to the serial terminal. The
sequence starts with 1 and 1, and the values in the sequence are:
1, 1, 2, 3, 5, 8, 13...
program the control flow to
implement the algorithm to output the Fibonacci sequence until the user force it to stop
Hint: the command is serial .write

It would be useful if you post the code you have already tried to write.

Also, be specific about what is the point you are struggling with?

the code:

// VARIABLES
const int button = 4; // button Pin
int buttonState; //hold the current state of button
int lastButtonState = HIGH; // store  previous state of button
int a = 1; // variables Fib. numbers
int b = 1; // the values for a and b seed for the sequence
int c; // next number in 
void setup()

{
pinMode(button,INPUT); // set button as input
Serial.begin(9600); // begin serial communication
delay(2000); // 2s delay
}

void loop()

{
buttonState = digitalRead(button); 
// if button is just pressed
if(buttonState == LOW && buttonState != lastButtonState)

{
c = a + b; // calculate next Fib. number
printNumbers(a,b,c); // send the last three values to the print function
a = b; // The last number becomes the second-to-last
b = c; // The new number becomes the last number in the list
}
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
}

I can only get one program to output one line by pressing the reset button which is 1 + 1 = 2

Write the sequence in plain language:

"One plus plus one equals two."

This "says" that two known values add up to the third value, so your program will need to start knowing "a" and "b"... and then calculate "c." You can do this many ways, but for this time, use just "a," "b," and "c" for your values. After the first calculation for "c", the value for "a" is not needed any more, so you can move "b" into "a" and move "c" into "b"... You also want a nice program format (for ease of reading the code), and a nice presentation (for ease of reading the output).

int a = 1;
int b = 1;
int c = 0;

void setup() {
  // put your setup code here, to run once:

  // Start the serial communications at 9.6k baud
  Serial.begin(9600);

  // Introduce the output (with a <Carriage Return> to give the numbers their own line
  Serial.println("The F* sequence: ");

  // Print the first known value
  Serial.print (a);
  // Put space between the values
  Serial.print (" ");
  // Print the second known value
  Serial.print (b);
  // Put space between the values
  Serial.print (" ");
}

void loop() {
  // put your main code here, to run repeatedly:

  // calculate the next value in the sequence
  c = a + b;

  // Print the next value
  Serial.print (c);
  // Put space between the values
  Serial.print (" ");

  // "a" is not needed, so move "b" into "a" and move "c" into "b"
  a = b;
  b = c;

  // Now go back to the top of the loop
}

Should be bool instead of int

Please, unclench your mind. Fibonacci had no computer, what did he do?

Start with 4 variables, unsigned longs to precisely handle numbers that get big.
unsigbed long varA, varB, varTotal, varLimit

in setup()
{
begin serial
varA = varB = 1
varLimit = 0xFFFFFFFF
Print varA and varB 1st 2 numbers.
}

Print each number on a single line or manage spacing yourself.

in loop()
{
varTotal = varA + varB
Print that as the next number.
Copy varB over varA
Copy varTotal over varB
delay( 250 )
}

This should crank the sequence out past 4 billion.

It's really just two numbers progressing, when you see that the difficulty to express that is code literacy to tell the machine what to do, every last detail because the machine is incredible as to speed and knowing nothing but what you give.

So first simplify the problem to cut down what you have to tell the machine.

If you think this is hard, try doing it by hand. Tedium for life!

1 Like

I think your problem here is that the switch may not be working the way you expect.

pinMode(button,INPUT);

Is your switch wired with an external pullup resistor? If not, then you need to specify INPUT_PULLUP.

if(buttonState == LOW && buttonState != lastButtonState)

This will only work ONCE (and it will look like nothing has stopped) because you are then setting lastButtonState to be the same as buttonState inside the if statement.

It is not clear from your statement is supposed to happen when you press the switch.

  • If you just want to pause while the switch is pressed, just check for LOW and skip the calculation while the switch is LOW.
  • If you want to turn it off forever with one press, then use a separate boolean variable that gets set when the switch is pressed and then check the boolean in the if statement.
  • If you want to toggle on/off then you will still need the separate boolean and toggle it true/false when you detect the switch has transitioned from LOW to HIGH and HIGH to LOW.

You have to implement the Fibonacci series algorithm starting from the mathematical definition (for example using a recursive function) and not do the sums as you would with the calculator!

image

In the code that OP seems to have "borrowed" from here, the author (one Luis Pato) has a comment:

Circuit:
     button to Arduino Pin4 (with pull-up resistor)

Perhaps @neon575 didn't see that requirement?

But the code as originally written, doesn't purport to do what's required here. The code as written produces the next 3 values in the sequence each time the button is pressed; @neon575 specifically says their assignment is to:

It might be easier, OP, to start from scratch writing the code the way you need it in the first place.

1. Get the definition of Fibonacci sequence.
It is a series of integer numbers in which the next number is the addition f the preceding two numbers given seed values 0 (F0 = 0) and 1 (F1 = 1). For example:
0, 1, 1, 2, 3, 5, 8, 13, ...

Mathematically,
Fn = Fn-1 + Fn-2 with F0 = 0, F1 = 1, and n = 2 and greater

2. The printing on the Serial Monitor will stop when S is issued from InputBox of the Serial Monitor or 20 Fibonacci numbers are printed whichever occurs earlier.

3. Solution (recursive Method):

unsigned long n = 0;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  unsigned long y = fib(n);
  Serial.print(y);
  Serial.print(',');
  n++;
  if(n == 20)   //20 Fibonacci numbers are printed; print no more numbers
  {
    while(1);
  }
  delay(1000);
}

unsigned long fib(unsigned long n)  //compute a Fibonacci number
{
  if (n <= 1)
  {
    return n;
  }
  else
  {
    unsigned long sum = fib(n - 1) + fib(n - 2);
    return sum;
  }
}

void serialEvent()   //to handle character coming from Serial Monitor
{
  if (Serial.available()>0)
  {
    if(Serial.read() == 'S')
    {
      while(1);    //wait here for indefinite period
    }
  }
}

You got the point, but I think it would have been better if the OP had come up with the algorithm using his skills and knowledge.

However, in my opinion the unsigned long sum local variable is redundant. You can return the result of the sum directly.

Is the above right when Fibonacci sequence starts with seed values 0 and 1?

As far as I know, Fibonacci sequence starts from 1 (the value 0 is not contemplated), so the image I've posted is wrong.
f(0) should be 0.

Terrible hint.

Ditto.

I agree with you fully; but, sometimes OP needs an example which may prompt him to ask inquisitive questions. I have reason to believe that OP has no idea about recursion (a difficult concept to digest how a program does call itself!); let's see if he asks question what is a recursion.

I have avoided nested codes for the convenience of reading.

By definition, a Fibonacci number is the addition of the preceding two numbers. So, if we don't include the seed numbers/values (0, 1) in the sequence how do we compute the index-2 number (the 1)? For example:
0, 1, 1, 2, 3, ...

1 Like

By that loose definition, should we include numbers further to the left on the number line?

Fibonacci sequence starts with seed values 0 and 1. So, there is no number beyond 1 (the index-0 number of Fibonacci sequence). I am not sure if the seed numbers are the members of the Fibonacci sequence though some articles show them.

Imnsho, implementing the algorithm recursively on an arduino Uno would be a mistake. Perhaps it is even a “trap” assignment, since that is the usual solution you’ll see online…

The code in #3 looks like it is on the right track for calculating the series (and the assignment was to calculate the series, so doing each number “from scratch” is particularly inefficient.). It sounds like it’s problem is with the button handling and perhaps printing.

Yes, becasue it seems to me the OP lifted some code from 2014 and while it has a button, what the 2014 author wanted to do is not the same as what the 2022 OP here wants to do :wink: