Nota
Ciao, benvenuto nella community SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts su Facebook! Approfondisci Raspberry Pi, Arduino ed ESP32 con altri appassionati.
Perché unirsi?
Supporto Esperto: Risolvi problemi post-vendita e sfide tecniche con l’aiuto della nostra community e del nostro team.
Impara & Condividi: Scambia consigli e tutorial per migliorare le tue competenze.
Anteprime Esclusive: Ottieni l’accesso anticipato agli annunci di nuovi prodotti e anteprime esclusive.
Sconti Speciali: Goditi sconti esclusivi sui nostri prodotti più recenti.
Promozioni e Concorsi Festivi: Partecipa a concorsi e promozioni festive.
👉 Pronto a esplorare e creare con noi? Clicca [Qui] e unisciti oggi stesso!
GIOCO - Indovina il Numero
Indovina il Numero è un divertente gioco da festa in cui tu e i tuoi amici vi alternate nell’inserire un numero (0~99). L’intervallo diventa più stretto ad ogni input fino a quando un giocatore indovina correttamente il numero. Il giocatore che indovina correttamente viene dichiarato perdente e soggetto a una penalità. Ad esempio, se il numero segreto è 51, che i giocatori non possono vedere, e il giocatore 1 inserisce 50, l’intervallo di numeri cambia a 50~99. Se il giocatore 2 inserisce 70, l’intervallo diventa 50~70. Se il giocatore 3 inserisce 51, è il perdente. In questo gioco, utilizziamo un telecomando a infrarossi per inserire i numeri e un LCD per visualizzare i risultati.
Componenti Necessari
In questo progetto, abbiamo bisogno dei seguenti componenti.
È sicuramente conveniente acquistare un kit completo, ecco il link:
Nome |
ELEMENTI IN QUESTO KIT |
LINK |
|---|---|---|
Elite Explorer Kit |
300+ |
Puoi anche acquistarli separatamente dai link sottostanti.
INTRODUZIONE COMPONENTI |
LINK ACQUISTO |
|---|---|
- |
|
Collegamenti
Schema Elettrico
Codice
Nota
Puoi aprire il file
10_guess_number.inonel percorsoelite-explorer-kit-main\fun_project\10_guess_numberdirettamente.Oppure copia questo codice nell’Arduino IDE.
Nota
Per installare la libreria, usa l’Arduino Library Manager e cerca «IRremote» e «LiquidCrystal I2C» e installale.
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}
Come funziona?
Importazioni Librerie e Definizioni delle Variabili Globali:
Vengono importate tre librerie:
Wireper la comunicazione I2C,LiquidCrystal_I2Cper il controllo del display LCD eIRremoteper ricevere i segnali dal telecomando a infrarossi. Sono definite diverse variabili globali per memorizzare lo stato e le impostazioni del gioco.setup()Inizializza il display LCD e accendi la retroilluminazione. Inizializza la comunicazione seriale con un baud rate di 9600. Avvia il ricevitore a infrarossi. Chiama la funzione
initNewValue()per impostare lo stato iniziale del gioco.loop()Controlla se è stato ricevuto un segnale dal telecomando a infrarossi. Decodifica il segnale infrarosso ricevuto. Aggiorna lo stato del gioco o esegui le azioni corrispondenti in base al valore decodificato (numero o comando).
initNewValue()Utilizza
analogReadper inizializzare il seme del numero casuale, garantendo che vengano generati numeri casuali diversi ogni volta. Genera un numero casuale tra 0 e 98 come numero fortunato (il numero che i giocatori devono indovinare). Reimposta i prompt dei limiti superiore e inferiore. Visualizza un messaggio di benvenuto sul display LCD. Reimposta il numero di input.detectPoint()Controlla la relazione tra il numero di input del giocatore e il numero fortunato. Se il numero di input è maggiore del numero fortunato, aggiorna il prompt del limite superiore. Se il numero di input è minore del numero fortunato, aggiorna il prompt del limite inferiore. Se il giocatore inserisce il numero corretto, reimposta l’input e restituisce true.
lcdShowInput()Visualizza l’input del giocatore e i prompt dei limiti superiore e inferiore correnti sul display LCD. Se il giocatore indovina correttamente, visualizza un messaggio di successo e pausa per 5 secondi prima di riavviare il gioco.