let me try this again, browser was missing the code buttons...etc... and to restart it...
I recently learned of using FSM from another member here. I have a FSM called selections.
in each case if I set "selection" equal to the next case it works fine. In my SELECT_WINER case I it counts up what will be a winning score as part of user settings. A button is pressed when it gets to the value you want., if you never press the button, it doesn't nothing then moves to the next selection.
here is the section I'm having an issue with, it always stops at the end of this. the function programSelections is called in the main loop.
case SELECT_WINNER:
int n = 10;
if (selectValue < 50) {
if ((millis() - selectValueLastTime) > selectionDuration) {
// Serial.print("Select Value: ");
// Serial.println(selectValue);
// once value hits 300 increment by 50
if (selectValue >= 300) {
n = 50;
}
selectValue += n;
toDisplay(selectValue, selections);
selectValueLastTime = millis();
}
if (knockOffPressed >= knockOffTime) {
winningScore = selectValue;
selections = SELECT_FREE;
musicPlayer.startPlayingFile(SOUND_10.c_str());
}
} else {
selections = SELECT_FREE;
Serial.print("new Selection: ");
Serial.println(selections);
}
break;
Here is the entire code
/*
Sketch title
Describe what it does in layman's terms. Refer to the components
attached to the various pins.
The circuit:
list the components attached to each input
list the components attached to each output
Created day month year
By author's name
Modified day month year
By author's name
http://url/of/online/tutorial.cc
*/
//VERSION NOTES
/*
11= started adding sounds
10 - added FSM dispenser code
9 - added ticket dispenser DOES NOT WORK!
7 - game loop complete, game start during flash score fixed.
8 - moved outputs to 8 ch relays
*/
//=======USER SETTINGS ==================================
//============ GAME SETTINGS ===============
//these are initial settings, then once changed will be saved on the MicroSd card.
int coinsReq = 1; // coins per game
int numberBalls = 6; // ballsper game, 6 or 9
int winningScore = 150; // plays winning song and lights winner sign, first ticket
int highScore = 250; // plays high score song and top flasher
int freeGameScore = 200; //must be higher than winning score
int ticketSpan = 30; //span between tickets
int numberTickets = 0; // no tickets per ticket interval, 0 = no tickets
boolean idleSong = false;
unsigned long idleSongInterval = 60000; //1000 = 1 sec, how long between songs
int highestScore = 50;
enum selections {SELECT_IDLE, SELECT_WINNER, SELECT_FREE,
SELECT_TICKET_SPAN, SELECT_NUMBER_TICKETS,
SELECT_IDLE_SONG, SELECT_NUMBER_COINS,
SELECT_HIGH_SCORE, SELECT_COMPLETE
} selections = SELECT_IDLE;
int selectValue = 0; // usedto increment selection values in program mode.
int i = 2;
//Sound Files
// file names must start with /
String SOUND_PWR = "/01_pwr.ogg";
String SOUND_START = "/02_start.ogg";
String SOUND_10 = "/03_sc_10.ogg";
String SOUND_20 = "/04_sc_20.ogg";
String SOUND_30 = "/05_sc_30.ogg";
String SOUND_40 = "/06_sc_40.ogg";
String SOUND_50 = "/07_sc_50.ogg";
String SOUND_100 = "/08_s_100.ogg";
String SOUND_GUTTER = "/09_gut.ogg";
String SOUND_WINNER = "/10_win.ogg";
String SOUND_HIGHSCORE = "/11_high.ogg";
String SOUND_IDLESONG = "/12_atrct.ogg";
//======= END USER SETTINGS ================================
//======= DO NOT CHANGE ANYTHING BELOW HERE! ==========
// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
// define the pins used
#define CLK 13 // SPI Clock, shared with SD card
#define MISO 12 // Input data, from VS1053/SD card
#define MOSI 11 // Output data, to VS1053/SD card
// Connect CLK, MISO and MOSI to hardware SPI pins.
// See http://arduino.cc/en/Reference/SPI "Connections"
// These are the pins used for the music maker shield
#define SHIELD_RESET -1 // VS1053 reset pin (unused!)
#define SHIELD_CS 7 // VS1053 chip select pin (output) was 7
#define SHIELD_DCS 6 // VS1053 Data/command select pin (output)
// These are common pins between breakout and shield
#define CARDCS 4 // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3 // VS1053 Data request, ideally an Interrupt pin
Adafruit_VS1053_FilePlayer musicPlayer =
// create shield-example object!
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);
//===== INTPUT =====
int knockPin = 26;
int coinPin = 28;
int scorePin = 30;
int bonusPin = 32;
int ballPin = 34;
int ticketNotchPin = 22;
int volumePin = A8;
//===== OUTPUT =====
int ballRel = 27;
int flasherLED = 29;
int winnerLED = 31;
int gameOverLED = 33;
int freeGameLED = 35;
int coinCounter = 37;
int ticketCounter = 39;
int DispenserMotorPin = 23;
//DISPLAY DATA PINS
const int dataPin = 24;
const int clockPin = 25;
//====== MISC VARIABLES
int coinsIn = 0;
int ballCount = 0;
int currentScore = 0;
int totalScore = 0 ;
boolean ballsReleased = false;
boolean winningSongPlayed = false;
boolean highScoreSongPlayed = false;
String gameMode = "boot"; //boot, program, gameRun, gameEnd
int lastKnockOffState = HIGH;
int flasherState = LOW;
int blinkState = LOW;
int coinSwState; // current state
int coinSwNewState; //newstate
int coinSwLastState = LOW;
int scoreSwState; // current state
int scoreSwNewState; //newstate
int scoreSwLastState = LOW;
int ballSwState; // current state
int ballSwNewState; //newstate
int ballSwLastState = LOW;
int bonusSwState; // current state
int bonusSwNewState; //newstate
int bonusSwLastState = LOW;
int ballReleaseState ; // current state
int ballReleaseLastState = HIGH;
// TICKET DISPENSER
const int MOTOR_ON = HIGH;
const int MOTOR_OFF = LOW;
const int IS_NOT_NOTCH = HIGH;
const int IS_NOTCH = LOW;
enum DispenserStates {IDLE, FIND_START_OF_TICKET,
FIND_END_OF_TICKET, FIND_END_OF_NOTCH,
TICKET_JAM, OUT_OF_TICKETS
} DispenserState = IDLE;
const unsigned long NOTCH_TIMEOUT = 300;
const unsigned long TICKET_TIMEOUT = 3000;
unsigned long DispenseTimer;
int ticketsEarned = 0;
int ticketsIssued = 0;
// TIMER SETTINGS
int inputDebounce = 5;
int long bootTimer = 5000; // how long before it goes into idle mode
int knockOffTime = 2000; //amount of time to hold down knock off switch
int knockOffPressed = 0; //how long knock off sw has been pressed
int ballReleaseDuration = 3000; // how long to hold ball release on, an be shorter for 6 balls
int flashDuration = 500; //used for flasher nad for display flash
unsigned long selectValueLastTime = 0; //used in prgramming selections as non blocking delay
unsigned long selectionDuration = 1000; // how long before moving to next value
unsigned long idleSongLast; //last time idel song was played
unsigned long coinSwLastTime = 0; //last state change
unsigned long scoreSwLastTime = 0;//last state change
unsigned long bonusSwLastTime = 0;//last state change
unsigned long ballSwLastTime = 0;//last state change
unsigned long knockOfflastTime = 0;//last state change
unsigned long ballReleaseLastTime = 0;//last state change
unsigned long blinkLastTime = 0;
unsigned long flashLastTime = 0;
unsigned long loopTime; //calcs the time the main loop takes
//DISPLAY SETTINGS
int spinDelay = 100;
unsigned long spinLastTime;
int s; // used for position in display spin
int bCnt; // use for blink count of freegame led and gameover led
int fCnt; // use for flasher count
int displayDelay = 10; // needed to slow display updates
unsigned long displayLastTime; // last time displayy was updated
//converts the numbers 0-9 to the correct Octal value for the 7-segment
// 0-9 AND A, C, E, H, L, P, -, blank
uint8_t numberToOctal[10] = {0b00111111, 0b00000011, 0b01101101, 0b01100111, 0b01010011, 0b01110110, 0b01111110, 0b00100011, 0b01111111, 0b01110011,};
uint8_t spinPos[7] = {0b00111111, 0b00111110, 0b00111101, 0b00111011, 0b00110111, 0b00101111, 0b00011111};
// A, C, E, H, L, P, -, blank
uint8_t letters[8] = {0b01111011, 0b00111100, 0b01111100, 0b01011011, 0b00011100, 0b01111001, 0b01000000, 0b00000000};
//Sound Settings
String songToPlay;
int volumeIn; //reading from volume pin
int volumeValue; // value to set volume too
//settings file
File myFile;
String settingsFile = "skeeball.txt";
//char printidleSongInterval[10];
//=================== SETUP =================
void setup(void) {
Serial.begin(115200);
pinMode(knockPin, INPUT);
pinMode(coinPin, INPUT);
pinMode(coinCounter, OUTPUT);
pinMode(ticketCounter, OUTPUT);
pinMode(ballRel, OUTPUT);
pinMode(gameOverLED, OUTPUT);
pinMode(winnerLED, OUTPUT);
pinMode(freeGameLED, OUTPUT);
pinMode(flasherLED, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(DispenserMotorPin, OUTPUT);
pinMode(ticketNotchPin, INPUT);
digitalWrite(DispenserMotorPin, LOW);
digitalWrite(ballRel, HIGH);
digitalWrite(gameOverLED, HIGH);
digitalWrite(freeGameLED, HIGH);
digitalWrite(flasherLED, HIGH);
digitalWrite(winnerLED, HIGH);
digitalWrite(coinCounter, HIGH);
digitalWrite(ticketCounter, HIGH);
//MP3 player settings
if (! musicPlayer.begin()) { // initialise the music player
Serial.println(F("Couldn't find VS1053"));
while (1);
}
Serial.println(F("VS1053 found"));
if (!SD.begin(CARDCS)) {
Serial.println(F("SD failed, or not present"));
while (1); // don't do anything more
}
//Load settings form SD card
//if no settings fiel found one will be created.
loadSettings();
// Set volume for left, right channels. lower numbers == louder volume!
//later controlled by volume potentiometer.
//musicPlayer.setVolume(90, 90);
volumeControl();
// If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
// audio playing
musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT); // DREQ int
//musicPlayer.sineTest(0x44, 500); // Make a tone to indicate VS1053 is working
if (! musicPlayer.startPlayingFile(SOUND_PWR.c_str())) {
Serial.print("Could not open file ");
Serial.println(SOUND_PWR);
while (1);
}
Serial.println ("SYSTEM BOOTED");
}
//========================================================================= MAIN LOOP =========================================================================
void loop(void) {
//set volume
volumeControl();
unsigned long currentTime = millis();
//=======Read inputs
// Boot mode only gives time to enter program mode.
if (gameMode == "boot") {
// Serial.println ("Game mode = boot");
if (currentTime < bootTimer) {
//software version dispaly
// Version 1010
toDisplay(101, 0);
//read knock off switch
knockOff();
//TODO remove these two
gameMode = "program";
} else {
gameMode = "idle";
}
//========================================================================= PROGRAM MODE =========================================================================
} else if (gameMode == "program") {
//Serial.println ("Game mode = program");
programSelections();
knockOff(); //monitor knock off switch
//========================================================================= GAME PLAY =========================================================================
} else if (gameMode == "gameRun") {
// Serial.print ("Game mode = game running");
// Serial.print (" - ball release status: ");
// Serial.println(ballsReleased);
//readInputs();
if (ballsReleased == true) {
digitalWrite(gameOverLED, HIGH);
//============SCORE SW INPUT=======================
scoreSwState = digitalRead(scorePin);
// If the switch changed:
if (scoreSwState != scoreSwLastState) {
// reset the debouncing timer
scoreSwLastTime = millis();
}
if ((millis() - scoreSwLastTime) > inputDebounce) {
// if the button state has changed:
if (scoreSwState != scoreSwNewState) {
scoreSwNewState = scoreSwState;
if (scoreSwNewState == LOW) {
currentScore += 10;
totalScore = totalScore += 10;
// Serial.print("Score: ");
// Serial.println(totalScore);
toDisplay(totalScore, ballCount);
}
}
}
// save the scoreSwState. Next time through the loop, it'll be the scoreSwLastState:
scoreSwLastState = scoreSwState;
//============SCORE SW INPUT=====================
//============BONUS SW INPUT=======================
bonusSwState = digitalRead(bonusPin);
// If the switch changed:
if (bonusSwState != bonusSwLastState) {
// reset the debouncing timer
bonusSwLastTime = millis();
}
if ((millis() - bonusSwLastTime) > inputDebounce) {
// if the button state has changed:
if (bonusSwState != bonusSwNewState) {
bonusSwNewState = bonusSwState;
if (bonusSwNewState == LOW) {
currentScore += 50;
totalScore = totalScore += 50;
toDisplay(totalScore, ballCount);
}
}
}
// save the bonusSwState. Next time through the loop, it'll be the bonusSwLastState:
bonusSwLastState = bonusSwState;
//============BONUS SW INPUT=====================
//============BALL INPUT=======================
ballSwState = digitalRead(ballPin);
// If the switch changed, due to noise or pressing:
if (ballSwState != ballSwLastState) {
// reset the debouncing timer
ballSwLastTime = millis();
}
if ((millis() - ballSwLastTime) > inputDebounce) {
// if the button state has changed:
if (ballSwState != ballSwNewState) {
ballSwNewState = ballSwState;
if (ballSwNewState == LOW && ballCount < numberBalls) {
ballCount += 1;
toDisplay(totalScore, ballCount);
Serial.print("Score Current, Total: ");
Serial.print(currentScore);
Serial.print(" , ");
Serial.print(totalScore);
Serial.print(" ball count: " );
Serial.println(ballCount);
//======== Play song for score =====
switch (currentScore) {
case 10:
Serial.println ("10 Song");
songToPlay = SOUND_10;
break;
case 20:
Serial.println ("20 Song");
songToPlay = SOUND_20;
break;
case 30:
Serial.println ("30 Song");
songToPlay = SOUND_30;
break;
case 40:
Serial.println ("40 Song");
songToPlay = SOUND_40;
break;
case 50:
Serial.println ("50 Song");
songToPlay = SOUND_50;
break;
case 100:
Serial.println ("100 Song");
songToPlay = SOUND_100;
break;
default:
Serial.println ("Gutter Ball Song");
songToPlay = SOUND_GUTTER;
break;
}
if (totalScore >= winningScore && totalScore < highScore && winningSongPlayed == false) {
Serial.println ("Winning Score Song");
//musicPlayer.stopPlaying();
songToPlay = SOUND_WINNER;
digitalWrite(winnerLED, LOW);
winningSongPlayed = true;
} else if (totalScore >= highScore && highScoreSongPlayed == false) {
Serial.println ("High Score Song");
//musicPlayer.stopPlaying();
songToPlay = SOUND_HIGHSCORE;
// highScoreSongPlayed = true;
}
if (! musicPlayer.startPlayingFile(songToPlay.c_str())) {
Serial.print("Could not open file ");
Serial.println(songToPlay);
while (1);
}
//}//============= End play song for score ===========
} else {
currentScore = 0;
}
}
}
// save the ballSwState. Next time through the loop, it'll be the ballSwLastState:
ballSwLastState = ballSwState;
if (ballCount == numberBalls) {
gameMode = "gameEnd";
Serial.println("all balls played, Game Over ");
//coinsIn = 0;
}
//============BALL INPUT=====================
// Calculate tickets
if (numberTickets > 0) {
if (totalScore >= winningScore) {
ticketsEarned = (((totalScore - winningScore) / ticketSpan) + 1) * numberTickets ;
dispense();
}
}
if (totalScore >= highScore && highScoreSongPlayed == false) {
flasherControl();
}
}//end balls released, game play loop
//========================================================================= GAME END =========================================================================
} else if (gameMode == "gameEnd") {
digitalWrite(gameOverLED, LOW);
if (totalScore > highestScore) {
highestScore = totalScore;
saveSettings();
}
//dispenserEnabled = false;
readCoins();
// Serial.println ("Game mode = game end");
//flash last score
if (bCnt <= 10 && ballsReleased == true) {
if ((millis() - blinkLastTime) > flashDuration) {
if (blinkState == HIGH) {
//Serial.println(" Flash ON");
toDisplay(totalScore, ballCount);
blinkState = LOW;
} else {
//Serial.println(" Flash OFF");
letterDisplay(letters[7], letters[7], letters[7], letters[7]);
blinkState = HIGH;
}
blinkLastTime = millis();
bCnt++;
}
} else {
gameMode = "idle";
}
//========================================================================= IDLE MODE =========================================================================
} else if (gameMode == "idle") {
//Serial.println ("Game mode = idle");
//Spin display
knockOff();
spinDisplay();
readCoins();
playIdelSong();
}// end game mode
//timer to check loop speed
// loopTime = millis() - currentTime;
// Serial.print("Loop Time: " );
// Serial.println(loopTime);
}// loop
//========================================================================= END MAIN LOOP =========================================================================
//===========================================================================SUB ROUTINES ======
void programSelections()
{
switch (selections)
{
case SELECT_IDLE:
selections = SELECT_WINNER;
break;
case SELECT_WINNER:
int n = 10;
if (selectValue < 50) {
if ((millis() - selectValueLastTime) > selectionDuration) {
// Serial.print("Select Value: ");
// Serial.println(selectValue);
// once value hits 300 increment by 50
if (selectValue >= 300) {
n = 50;
}
selectValue += n;
toDisplay(selectValue, selections);
selectValueLastTime = millis();
}
if (knockOffPressed >= knockOffTime) {
winningScore = selectValue;
selections = SELECT_FREE;
musicPlayer.startPlayingFile(SOUND_10.c_str());
}
} else {
selections = SELECT_FREE;
Serial.print("new Selection: ");
Serial.println(selections);
}
break;
case SELECT_FREE:
Serial.print("Selection FREE: ");
Serial.println(selections);
selections = SELECT_TICKET_SPAN;
break;
case SELECT_TICKET_SPAN:
Serial.print("Selection SPAN: ");
Serial.println(selections);
selections = SELECT_NUMBER_TICKETS;
break;
case SELECT_NUMBER_TICKETS:
Serial.print("Selection NUMBER TICKETS: ");
Serial.println(selections);
selections = SELECT_IDLE_SONG;
break;
case SELECT_IDLE_SONG:
break;
case SELECT_NUMBER_COINS:
break;
case SELECT_HIGH_SCORE:
break;
}
}
void dispense()
{
switch (DispenserState)
{
case IDLE:
Serial.println("IDLE State: ");
if (ticketsIssued < ticketsEarned)
{
DispenserState = FIND_START_OF_TICKET;
DispenseTimer = millis();
digitalWrite(DispenserMotorPin, MOTOR_ON);
}
break;
case FIND_START_OF_TICKET:
// If we don't get out of the 'notch' we are probably
// out of tickets or jammed at a notch.
//Serial.println("FIND_START_OF_TICKET State: ");
if (millis() - DispenseTimer >= NOTCH_TIMEOUT)
{
digitalWrite(DispenserMotorPin, MOTOR_OFF);
DispenserState = OUT_OF_TICKETS;
}
else
// If we start in a notch, drive until the end of a notch is found
if (digitalRead(ticketNotchPin) == IS_NOT_NOTCH)
{
DispenserState = FIND_END_OF_TICKET;
DispenseTimer = millis();
}
break;
case FIND_END_OF_TICKET:
// If we don't get to the end of the ticket we are
// probably jammed.
//Serial.println("FIND_END_OF_TICKET State: ");
if (millis() - DispenseTimer >= TICKET_TIMEOUT)
{
digitalWrite(DispenserMotorPin, MOTOR_OFF);
DispenserState = TICKET_JAM;
}
else
// Dispense the ticket until the end notch is found
if (digitalRead(ticketNotchPin) == IS_NOTCH)
{
// The ticket has been dispensed!
//RemainingToDispense--;
ticketsIssued += 1;
digitalWrite(ticketCounter, LOW);
delay(20);
digitalWrite(ticketCounter, HIGH);
DispenserState = FIND_END_OF_NOTCH;
DispenseTimer = millis();
}
break;
case FIND_END_OF_NOTCH:
// If we don't get out of the 'notch' we are probably
// out of tickets or jammed at a notch.
if (millis() - DispenseTimer >= NOTCH_TIMEOUT)
{
digitalWrite(DispenserMotorPin, MOTOR_OFF);
DispenserState = OUT_OF_TICKETS;
}
else if (digitalRead(ticketNotchPin) == IS_NOT_NOTCH)
{
digitalWrite(DispenserMotorPin, MOTOR_OFF);
DispenserState = IDLE;
}
break;
case TICKET_JAM:
Serial.println("TICKET JAM ");
break;
case OUT_OF_TICKETS:
Serial.println("OUT OF TICKETS ");
break;
}
}
void resetGame() {
fCnt = 0; // flasher count
bCnt = 0; // blink count
ballCount = 0;
totalScore = 0;
coinsIn = 0;
ticketsEarned = 0;
ticketsIssued = 0;
ballsReleased = false;
digitalWrite(gameOverLED, HIGH);
digitalWrite(freeGameLED, HIGH);
digitalWrite(winnerLED, HIGH);
digitalWrite(flasherLED, HIGH); //TODO CHANGE BACK TO HIGH FOR RELAY
highScoreSongPlayed = false;
winningSongPlayed = false;
DispenserState = IDLE;
}
void knockOff() {
int knockOffState = digitalRead(knockPin);
unsigned long currentTime = millis();
//======== KNOCK OFF SWITCH
// If the switch is pressed:
if (knockOffState != lastKnockOffState) {
// reset the timer
knockOfflastTime = millis();
//Serial.println("last time pressed");
}
if (knockOffState == LOW) {
knockOffPressed = currentTime - knockOfflastTime;
//Serial.print("time pressed: " ); Serial.println(knockOffPressed);
} else {
knockOffPressed = 0;
}
// save the knockOffState. Next time through the loop, it'll be the lastKnockOffState:
lastKnockOffState = knockOffState;
//======== KNOCK OFF SWITCH
if (gameMode == "boot") {
if (knockOffPressed >= knockOffTime) {
// if in boot mode then enter program mode
//Serial.println("change to program mode");
gameMode = "program";
}
} else if (gameMode == "idle") {
if (knockOffState == LOW) {
//display last score
toDisplay(totalScore, ballCount);
}
}
}
void readCoins() {
// Serial.println("Read coins " );
//============COIN INPUT=======================
coinSwState = digitalRead(coinPin);
// If the switch changed, due to noise or pressing:
if (coinSwState != coinSwLastState) {
// reset the debouncing timer
coinSwLastTime = millis();
}
if ((millis() - coinSwLastTime) > inputDebounce) {
// if the button state has changed:
if (coinSwState != coinSwNewState) {
coinSwNewState = coinSwState;
//Serial.println("Coin PRESSED: ");
if (coinSwNewState == LOW) {
coinsIn++;
Serial.print("Coin in: ");
Serial.println(coinsIn);
digitalWrite(coinCounter, LOW);
delay(20);
digitalWrite(coinCounter, HIGH);
if (coinsIn >= coinsReq) {
// f = 10; // stop flashing score
ballRelease();
coinSwLastTime = 0;
}
}
}
}
// save the coinSwState. Next time through the loop, it'll be the coinSwLastState:
coinSwLastState = coinSwState;
//============COIN INPUT=======================
}
void ballRelease() {
resetGame();
gameMode = "gameRun";
Serial.println("-- GAME STARTED --: ");
musicPlayer.startPlayingFile(SOUND_START.c_str());
if (ballsReleased == false) {
digitalWrite(gameOverLED, LOW);
digitalWrite(ballRel, LOW);
letterDisplay(letters[6], letters[6], letters[6], letters[6]);
delay(1000);
//Display highest score saved.
toDisplay(highestScore, ballCount);
//Serial.println("Release Balls On");
delay(ballReleaseDuration);
// if (millis() - ballReleaseLastTime >= ballReleaseDuration) {
digitalWrite(ballRel, HIGH);
ballsReleased = true;
toDisplay(totalScore, ballCount);
Serial.println("Release Balls OFF");
}
}
void playIdelSong() {
// =========== IDLE SONG TIMER ===========
// this stop song from playing as soon as game over
if (idleSong) {
if (idleSongLast == 0) {
idleSongLast = millis();
}
if (millis() - idleSongLast >= idleSongInterval) {
idleSongLast = millis();
Serial.println("-- Play idle song");
musicPlayer.startPlayingFile(SOUND_IDLESONG.c_str());
} else {
// Serial.println("idle song timer on");
}
// =========== IDLE SONG TIMER ===========
}
}
//TO SEND SCORE TO DISPLAY
void toDisplay(int totalScore, int ballCount) {
//break down score for display
int ones = (totalScore % 10);
int tens = ((totalScore / 10) % 10);
int hundreds = ((totalScore / 100) % 10);
shiftOut(dataPin, clockPin, LSBFIRST, numberToOctal[ballCount]);
shiftOut(dataPin, clockPin, LSBFIRST, numberToOctal[ones]);
shiftOut(dataPin, clockPin, LSBFIRST, numberToOctal[tens]);
shiftOut(dataPin, clockPin, LSBFIRST, numberToOctal[hundreds]);
delay (displayDelay); // must have delay here
}
void letterDisplay(uint8_t hundreds, uint8_t tens, uint8_t ones, uint8_t balls) {
shiftOut(dataPin, clockPin, LSBFIRST, balls);
shiftOut(dataPin, clockPin, LSBFIRST, ones);
shiftOut(dataPin, clockPin, LSBFIRST, tens);
shiftOut(dataPin, clockPin, LSBFIRST, hundreds);
delay (displayDelay); // must have delay here
}
void spinDisplay() {
//=========NON-BLOCKING SPIN
if ((millis() - spinLastTime) > spinDelay) {
if (s <= 6) {
//toDisplay(spinPos[s], spinPos[s], spinPos[s], spinPos[s]);
shiftOut(dataPin, clockPin, LSBFIRST, spinPos[s]);
shiftOut(dataPin, clockPin, LSBFIRST, spinPos[s]);
shiftOut(dataPin, clockPin, LSBFIRST, spinPos[s]);
shiftOut(dataPin, clockPin, LSBFIRST, spinPos[s]);
spinLastTime = millis();
s++;
} else {
s = 0;
}
}
//blink lights on/off
digitalWrite(winnerLED, HIGH);
if (bCnt <= 10) {
if ((millis() - blinkLastTime) > flashDuration) {
if (blinkState == HIGH) {
//off
//Serial.println(" OFF");
digitalWrite(gameOverLED, LOW);
digitalWrite(freeGameLED, HIGH);
blinkState = LOW;
} else {
//on
//Serial.println(" ON");
digitalWrite(gameOverLED, HIGH);
digitalWrite(freeGameLED, LOW);
blinkState = HIGH;
}
blinkLastTime = millis();
bCnt++;
}
} else {
bCnt = 0;
}
}
void flasherControl()
{
//blink flasher on/off
if (fCnt <= 10) {
if ((millis() - flashLastTime) > flashDuration) {
if (flasherState == HIGH) {
//on
Serial.println("FLASER ON");
digitalWrite(flasherLED, LOW);
flasherState = LOW;
} else {
//off
Serial.println("FLASER OFF");
digitalWrite(flasherLED, HIGH);
flasherState = HIGH;
}
flashLastTime = millis();
fCnt++;
}
}
else {
//fCnt = 0;
digitalWrite(flasherLED, HIGH);
highScoreSongPlayed = true;
}
}
void volumeControl() {
volumeIn = analogRead(volumePin);
// this makes the max 100
if (volumeIn > 1000) {
volumeIn = 1000;
} else if (volumeIn < 50) {
volumeIn = 50;
}
// divid value by 10 so in hte range of 0 - 100
volumeValue = (volumeIn / 10);
//set the volume
musicPlayer.setVolume(volumeValue, volumeValue);
}
void loadSettings()
{
// re-open the file for reading:
myFile = SD.open(settingsFile);
if (myFile) {
Serial.print("--Reading settings file: ");
Serial.println(settingsFile);
// read from the file
char buffer[40]; // May need to be a bit bigger if you have long names
byte index = 0;
while (myFile.available())
{
char c = myFile.read();
if (c == '\n' || c == '\r') // settings for <cr> and <lf>
{
parseAndSave(buffer);
index = 0;
buffer[index] = '\0'; // Keep buffer NULL terminated
}
else
{
buffer[index++] = c;
buffer[index] = '\0'; // Keep buffer NULL terminated
}
}
myFile.close(); // close the file:
// sprintf(printidleSongInterval, "%lu", idleSongInterval );
// Serial.print("coinsReq = "); Serial.println(coinsReq);
// Serial.print("numberBalls= "); Serial.println(numberBalls);
// Serial.print("winningScore = "); Serial.println(winningScore);
// Serial.print("highScore = "); Serial.println(highScore);
// Serial.print("freeGameScore = "); Serial.println(freeGameScore);
// Serial.print("ticketSpan = "); Serial.println(ticketSpan);
// Serial.print("numberTickets = "); Serial.println(numberTickets);
// Serial.print("idleSong = "); Serial.println(idleSong);
// Serial.print("idleSongInterval = "); Serial.println (printidleSongInterval);
// Serial.print("highestScore = "); Serial.println(highestScore);
} else {
Serial.print(settingsFile);
Serial.println(" doesn't exist, we're creating one. "); // if the file didn't open, print an error:
//save setting to create a file
saveSettings();
}
}
void saveSettings()
{
SD.remove(settingsFile) ; // if file is present delete it before writing new data
myFile = SD.open(settingsFile, FILE_WRITE); // open the file.
if (myFile) {
Serial.print("Writing to settings file: "); // if the file opened okay, write to it:
Serial.println(settingsFile);
myFile.print("coinsReq = "); myFile.println(coinsReq);
myFile.print("numberBalls= "); myFile.println(numberBalls);
myFile.print("winningScore = "); myFile.println(winningScore);
myFile.print("highScore = "); myFile.println(highScore);
myFile.print("freeGameScore = "); myFile.println(freeGameScore);
myFile.print("ticketSpan = "); myFile.println(ticketSpan);
myFile.print("numberTickets = "); myFile.println(numberTickets);
myFile.print("idleSong = "); myFile.println(idleSong);
myFile.print("idleSongInterval = "); myFile.println(idleSongInterval);
myFile.print("highestScore = "); myFile.println(highestScore);
myFile.close(); Serial.println("Settings saved!"); // close the file:
} else {
Serial.println("error opening settings file"); // if the file didn't open, print an error:
}
}
void parseAndSave(char *buff)
{
char *name = strtok(buff, " =");
if (name)
{
char *junk = strtok(NULL, " ");
if (junk)
{
char *valu = strtok(NULL, " ");
if (valu)
{
int val = atoi(valu);
if (strcmp(name, "coinsReq") == 0)
{
coinsReq = val;
}
if (strcmp(name, "numberBalls") == 0)
{
numberBalls = val;
}
if (strcmp(name, "winningScore") == 0)
{
winningScore = val;
}
if (strcmp(name, "highScore") == 0)
{
highScore = val;
}
if (strcmp(name, "freeGameScore") == 0)
{
freeGameScore = val;
}
if (strcmp(name, "ticketSpan") == 0)
{
ticketSpan = val;
}
if (strcmp(name, "numberTickets") == 0)
{
numberTickets = val;
}
if (strcmp(name, "idleSong") == 0)
{
idleSong = val;
}
if (strcmp(name, "idleSongInterval") == 0)
{
idleSongInterval = val;
}
else if (strcmp(name, "highestScore") == 0)
{
highestScore = val;
}
}
}
}
}