# Hold a random number

I am trying to create a code that has at least 6 servos attached and two buttons for a two player game. I want to be able to roll a random number and have it hold that value then when it is that players turn. The program should also take that previous number and add it to the next. It would eventually be adding up all the values of the rolls. This is what I have so far. Any advice would be helpful. Thanks!

``````#include <Servo.h>

Servo myservo;

int pos = 0;    // variable to store the servo position
int x;
int button = 8;
int BUTTON;
int randomNumber;
int xPrevious;

void setup() {
pinMode(button, INPUT);
Serial.begin(9600);
}

void loop() {
for (x = 2; x <= 7; x += 1) {
myservo.attach(x);

for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos);              // tell servo to go to position in variable 'pos'
delay(15);                       // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos);              // tell servo to go to position in variable 'pos'
delay(15);                       // waits 15ms for the servo to reach the position

if(BUTTON == LOW){
randomNumber = random(1,7);
delay(350);
Serial.println(randomNumber);
}
}
randomNumber += xPrevious;
}
}
``````

You are redefining the random number wrongly each time with

``````randomNumber += xPrevious;
``````

this is an error. You need another new variable (initialised at 0) to keep the running totals of all the random "rolls". You should be able to fix your program now you know this. Maybe something like

``````TotalofTherandomNumbers += xPrevious;
``````

to start off with.

You may also want to add in the after the line

`````` randomNumber = random(1,7);
``````

a new function, of yours, that takes random value randomNumber do the action in the game, what ever that is, depending on if its the first or second player.

Your xPrevious is declared but never given any value.

Is this what you're looking for?

``````    randomNumber += random(1,7);
``````

Another thing is that you should not assume that randomNumber is initialized to 0. Better assign it a starting value.

``````    int randomNumber = 0;   // or whatever you want
``````

Lastly, an Arduino int is a 2 bytes signed number. If the game goes on for a long time the variable will roll over at 32,767. Consider making it a unsigned long instead.