Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

GAME - Guess Number

Guessing Numbers is an entertaining party game where you and your friends take turns entering a number (0~99). The range becomes narrower with each number input until a player correctly guesses the answer. The player who guesses correctly is declared the loser and subjected to a penalty. For instance, if the secret number is 51, which the players cannot see, and player 1 inputs 50, the number range prompt changes to 50~99. If player 2 inputs 70, the number range becomes 50~70. If player 3 inputs 51, they are the unlucky one. In this game, we use an IR Remote Controller to input numbers and an LCD to display outcomes.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

Elite Explorer Kit

300+

Elite Explorer Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

Arduino Uno R4 WiFi

-

Breadboard

BUY

Jumper Wires

BUY

I2C LCD1602

BUY

Infrared Receiver

BUY

Wiring

../_images/10_guess_number_bb.png

Schematic

../_images/10_guess_number_schematic.png

Code

Note

  • You can open the file 10_guess_number.ino under the path of elite-explorer-kit-main\fun_project\10_guess_number directly.

  • Or copy this code into Arduino IDE.

Note

To install the library, use the Arduino Library Manager and search for “IRremote” and “LiquidCrystal I2C” and install them.

10_guess_number.ino
  1/*
  2  This code is for an Arduino Uno R4 board setup with an I2C LCD1602 display 
  3  and an Infrared (IR) Receiver. The program facilitates a guessing game where 
  4  a random number is generated. The user then uses an IR remote control to guess 
  5  this number. Feedback is provided on the LCD1602 display, and the generated 
  6  random number is also displayed on the Serial Monitor.
  7
  8  Board: Arduino Uno R4 
  9  Component: I2C LCD1602 and Infrared Receiver
 10  Library: https://www.arduino.cc/reference/en/libraries/liquidcrystal-i2c/ (LiquidCrystal I2C by Frank de Brabander)
 11           https://github.com/Arduino-IRremote/Arduino-IRremote (IRremote by shirriff, z3t0, ArminJo)
 12*/
 13
 14
 15#include <Wire.h>
 16#include <LiquidCrystal_I2C.h>
 17#include <IRremote.h>
 18
 19const int IR_RECEIVE_PIN = 5;  // Define the pin number for the IR Sensor
 20String lastDecodedValue = "";  // Variable to store the last decoded value
 21
 22LiquidCrystal_I2C lcd(0x27, 16, 2);
 23
 24// Variables for game state
 25int currentGuess = 0;       // Current input number
 26int pointValue = 0;  // Target number
 27int upper = 99;      // Current upper limit for guessing
 28int lower = 0;       // Current lower limit for guessing
 29
 30void setup() {
 31  lcd.init();
 32  lcd.backlight();
 33  Serial.begin(9600);                                     // Start serial communication at 9600 baud rate
 34  IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK);  // Start the IR receiver
 35  initNewValue();                                         // Initialize a new game round
 36}
 37
 38void loop() {
 39  if (IrReceiver.decode()) {
 40    bool numberMatched = 0;
 41    // Serial.println(IrReceiver.decodedIRData.command);
 42    String num = decodeKeyValue(IrReceiver.decodedIRData.command);
 43    if (num != "ERROR" && num != lastDecodedValue) {
 44      Serial.println(num);
 45      lastDecodedValue = num;  // Update the last decoded value
 46    }
 47
 48    // Handle different IR commands
 49    if (num == "POWER") {
 50      initNewValue();  // Start new game if POWER button pressed
 51    } else if (num == "CYCLE") {
 52      numberMatched = detectPoint();
 53      lcdShowInput(numberMatched);
 54    } else if (num >= "0" && num <= "9") {
 55      currentGuess = currentGuess * 10;
 56      currentGuess += num.toInt();
 57      if (currentGuess >= 10) {
 58        numberMatched = detectPoint();
 59      }
 60      lcdShowInput(numberMatched);
 61    }
 62    IrReceiver.resume();  // Enable receiving of the next value
 63  }
 64}
 65
 66void initNewValue() {
 67
 68  // Generate a new target number
 69  randomSeed(analogRead(A0));  // Seed random number generator
 70  pointValue = random(99);     // Generate target number
 71
 72  upper = 99;
 73  lower = 0;
 74
 75  // Display welcome message
 76  lcd.clear();
 77  lcd.print("    Welcome!");
 78  lcd.setCursor(0, 1);
 79  lcd.print("  Guess Number!");
 80
 81  currentGuess = 0;
 82
 83  // Output target for debugging
 84  Serial.print("point is ");
 85  Serial.println(pointValue);
 86}
 87
 88bool detectPoint() {
 89  // Check if guess is correct, too high, or too low
 90  if (currentGuess > pointValue) {
 91    if (currentGuess < upper) upper = currentGuess;
 92  } else if (currentGuess < pointValue) {
 93    if (currentGuess > lower) lower = currentGuess;
 94  } else if (currentGuess == pointValue) {
 95    currentGuess = 0;
 96    return true;
 97  }
 98  currentGuess = 0;
 99  return false;
100}
101
102void lcdShowInput(bool numberMatched) {
103  lcd.clear();
104  if (numberMatched == 1) {
105    lcd.setCursor(0, 0);
106    lcd.print("The number is ");
107    lcd.print(pointValue);
108    lcd.setCursor(0, 1);
109    lcd.print(" You've got it! ");
110    delay(5000);
111    initNewValue();
112    return;
113  }
114  lcd.print("Enter number:");
115  lcd.print(currentGuess);
116  lcd.setCursor(0, 1);
117  lcd.print(lower);
118  lcd.print(" < Point < ");
119  lcd.print(upper);
120}
121
122
123String decodeKeyValue(long irCode) {
124  // Map IR codes to corresponding commands
125  switch (irCode) {
126    case 0x16:
127      return "0";
128    case 0xC:
129      return "1";
130    case 0x18:
131      return "2";
132    case 0x5E:
133      return "3";
134    case 0x8:
135      return "4";
136    case 0x1C:
137      return "5";
138    case 0x5A:
139      return "6";
140    case 0x42:
141      return "7";
142    case 0x52:
143      return "8";
144    case 0x4A:
145      return "9";
146    case 0x9:
147      return "+";
148    case 0x15:
149      return "-";
150    case 0x7:
151      return "EQ";
152    case 0xD:
153      return "U/SD";
154    case 0x19:
155      return "CYCLE";
156    case 0x44:
157      return "PLAY/PAUSE";
158    case 0x43:
159      return "FORWARD";
160    case 0x40:
161      return "BACKWARD";
162    case 0x45:
163      return "POWER";
164    case 0x47:
165      return "MUTE";
166    case 0x46:
167      return "MODE";
168    case 0x0:
169      return "ERROR";
170    default:
171      return "ERROR";
172  }
173}

How it works?

  1. Library Imports and Global Variable Definitions:

    Three libraries are imported: Wire for I2C communication, LiquidCrystal_I2C for controlling the LCD display, and IRremote for receiving signals from the infrared remote controller. Several global variables are defined to store the game’s state and settings.

  2. setup()

    Initialize the LCD display and turn on the backlight. Initialize serial communication with a baud rate of 9600. Start the infrared receiver. Call the initNewValue() function to set the initial game state.

  3. loop()

    Check if a signal is received from the infrared remote controller. Decode the received infrared signal. Update the game state or perform corresponding actions based on the decoded value (number or command).

  4. initNewValue()

    Use analogRead to initialize the random number seed, ensuring different random numbers are generated each time. Generate a random number between 0 and 98 as the lucky number (the number players need to guess). Reset upper and lower limit prompts. Display a welcome message on the LCD. Reset the input number.

  5. detectPoint()

    Check the relationship between the player’s input number and the lucky number. If the input number is greater than the lucky number, update the upper limit prompt. If the input number is smaller than the lucky number, update the lower limit prompt. If the player inputs the correct number, reset the input and return true.

  6. lcdShowInput()

    Display the player’s input and the current upper and lower limit prompts on the LCD. If the player guesses correctly, display a success message and pause for 5 seconds before restarting the game.