// Project 17 - Making a Binary Quiz Game
#include <SPI.h>
#include <Streaming.h>
Print &cout {Serial};
//
// Global constant(s)
//
namespace gc {
//SPI Pin 11 -> DS (Data) ; Pin 13 -> SHCP (Latch)
constexpr uint8_t CsPin {10}; // SPI CS PIN (STCP) Clock
}
//
// Show the bit pattern (LEDs) by shifting the value to the 74HC595
//
void displayNumber(uint8_t value)
{
digitalWrite(gc::CsPin, LOW);
SPI.transfer(value);
digitalWrite(gc::CsPin, HIGH);
}
//
// receive the Answer from the player
//
uint8_t getAnswer()
{
char Character {0};
uint8_t Answer {0};
Serial.flush();
while (Serial.available() == 0) {} // do nothing until something comes into the serial buffer
while (Serial.available() > 0) // one Character of serial data is available, begin calculating
{
Character = Serial.read();
if (Character == '\n') {
break;
} else {
Answer *= 10;
Character -= '0';
Answer += Character;
}
delay(5); // allow a short delay for any more numbers to come into Serial.available
}
cout << "You entered: " << Answer << endl;
return Answer;
}
//
// check the Answer from the player and show the results
//
void checkAnswer(uint8_t Answer, uint8_t Number) {
(Answer == Number) ? cout << "Correct :-)" : cout << "Incorrect :-(";
cout << " -> " << _WIDTHZ(_BIN(Number),8) << " equals " << Number << endl << endl;
delay(10000); // give the player time to review his or her answers
}
void setup()
{
pinMode(gc::CsPin, OUTPUT);
SPI.begin();
Serial.begin(115200);
randomSeed(analogRead(0)); // initialize the random number generator
displayNumber(0); // clear the LEDs
}
void loop()
{
uint8_t Num = random(256);
displayNumber(Num);
cout << "What is the binary number in base-10? " << endl;
checkAnswer(getAnswer(), Num);
}