// magic8ball Uno/Nano, LCD1602, pushbutton
#include <LiquidCrystal.h> // LCD SPI library
byte rs = 12, en = 10, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // LCD pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // create object
uint8_t COLS = 16, ROWS = 2;
const byte switchPin = 6;
bool switchState = 0;
bool prevSwitchState = 0;
uint8_t reply;
uint8_t readtime = 5; // seconds for reading answer
const char *title[] = { "Ask the", "Crystal Ball" };
const char *answer[] = { "Yes", "Most likely", "Certainly", "Outlook good", "Unsure", "Negative", "Doubtful", "No" };
uint8_t smaldig[][8] = {
// each custom char has 8 elements
{ 0, 0, 0, 2, 6, 2, 2, 7 }, // small "1"
{ 0, 0, 0, 6, 1, 2, 4, 7 }, // small "2"
{ 0, 0, 0, 6, 1, 2, 1, 6 }, // small "3"
{ 0, 0, 0, 1, 3, 7, 1, 1 }, // small "4"
{ 0, 0, 0, 7, 4, 6, 1, 6 }, // small "5"
};
void setup() {
for (uint8_t i = 0; i < 5; i++) // count to three
lcd.createChar(i + 1, smaldig[i]); // create custom characters
lcd.begin(COLS, ROWS); // start the LCD
pinMode(switchPin, INPUT_PULLUP); // PRESSED = LOW, RELEASED = HIGH
randomSeed(analogRead(A0)); // add pseudo randomness
ask(); // show the title
}
void loop() {
switchState = digitalRead(switchPin); // read button state
if (switchState != prevSwitchState) { // if button state changes
if (switchState == LOW) { // if button was pressed
reply = random(8); // find the answer
center("The ball says:", 0);
scramble(); // flip random answers
center(answer[random(8)], 1); // display the answer
for (byte i = 0; i < readtime; i++) { // delay to read answer
lcd.setCursor(15, 1); // place countdown
lcd.write(readtime - i); // show countdown
delay(1000);
}
ask(); // restart it
}
}
prevSwitchState = switchState; // store button state
}
void ask() {
lcd.clear();
for (byte i = 0; i < 2; i++)
center(title[i], i);
}
void center(const char *text, byte row) {
lcd.setCursor((COLS - strlen(text)) / 2, row); // center text on LCD
lcd.print(text);
}
void scramble() { // show random answers
for (uint8_t i = 0; i < 20; i++) {
center(answer[random((sizeof(answer) / sizeof(answer[0])))], 1);
delay(500 / (sizeof(answer) / sizeof(answer[0]))); // one second of words
center(" ", 1);
}
}PRESS