Score , Highscore & LCD - JuliaElizabethLittle/peeMarksmanship GitHub Wiki
We now had a bit of code that calculated the score of our sensors, and a bit of code that could print Hello World! to our LCD display (very useful!)
So we wanted to join them. But first we cleared up a bit the score code. We included Arrays and got rid of everything that wasn't useful. The first bit had to of course include the LiquidCrystal library and the array for the screen
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Then we declare an array with three positions called sensors
and we keep the chain (the pushbutton):
int sensors[3];
int chain;
We don't change anything from the setup, we simply combine both the existing ones:
void setup() {
pinMode(button, INPUT_PULLUP);
Serial.begin(9600);
lcd.begin(16, 2);
}
And now here come the changes! First of all we used to have:
sensorA = analogRead (A0);
sensorA = map(sensorA,0,1023,0,10);
if (sensorA > 0){
score = sensorA*20;
}
The thing is, if the sensor has a value of 0, since there is a multiplication later on, the value would still be 0. so it's basically redundant. Also say that sensorA
is the value detected by A0, and we later map it out, when it can be much more efficiently written like this:
sensors[0] = map(analogRead(A0), 0, 1023, 0, 10);
score = sensors[0] * 20;
Since sensorA
would be in the first position of the array (position 0) we say: sensor[0]
and we directly map our it's value introducing the first variable to be A0
and then directly set the score
to be the value of the sensor times 20.
Once we cleared up all the code, and also introduced the high score system the whole thing looked like this:
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int counter = 0;
int lastscore = 0;
int score = 0;
int highscore = 0;
int sensors[3];
const int button = 7;
int chain;
void setup() {
pinMode(button, INPUT_PULLUP);
Serial.begin(9600);
lcd.begin(16, 2);
}
void loop() {
sensors[0] = map(analogRead(A0), 0, 1023, 0, 10);
score = sensors[0] * 20;
sensors[1] = map(analogRead (A1), 0, 1023, 0, 10);
score = score + sensors[1] * 10;
sensors[2] = map(analogRead (A2), 0, 1023, 0, 10);
score = score + sensors[2] * 5;
chain = digitalRead(button);
if (chain == LOW) {
counter = 0;
if(highscore<score) highscore = score;
lcd.clear();
lcd.print(score);
delay(1000)
}
if (score==lastscore){
counter+=1;
if (counter>=50) {
lcd.clear();
lcd.print("highscore: ");
lcd.print(highscore);
}
}
lastscore=score;
delay(100);
}
Then we tried out the twitter thing.