Arduino Slot Machine Using an LCD Display by Abdullah

by 929359 in Circuits > Arduino

29 Views, 1 Favorites, 0 Comments

Arduino Slot Machine Using an LCD Display by Abdullah

IMG_7045.png
IMG_7044.png

Imagine a slot machine where you don’t have to fear losing anything. I decided to base my project on an Arduino based slot machine that mimics the gambling style machine in casinos known as the slot machine by using electronics and code. It utilizes a 16x2 I2C LCD screen to display a variety of symbols, push buttons to control each reel on the LCD, LEDs conveying if someone has slight won, lost, or won, and I also added a buzzer for extra details. The objective of this game is to press one of the buttons which displays the start symbol to activate the game and to spin each reel, then press the buttons in labeled order to stop spinning of each reel. The final result is based off whether the 3 reels are matching or not. This game includes a lot of animation, real time input, hardware interaction, and game logic into one system. The game was created to ensure an easier method of learning Arduino interactively utilizing concepts of coding such as loops specifically, conditionals, random number generation which I personally didn’t understand extremely well before creating this project, into a real life interactive gambling game. After reading my step by step instructions you will be able to create your own personal efficient slot machine with ease.

Before getting started you will need utilize the components I will list below to ensure you can make the best possible slot machine. Majority of the parts I list can be easily found through places like Amazon and/or Home Depot, any place where they sell computer components.



Supplies

IMG_7046.jpeg

ComponentQuantityPurposeApproximate Cost (CAD)

Arduino Uno R3

1

Main microcontroller that controls the entire slot machine

$15–30

16×2 I2C LCD Display

1

Displays slot machine symbols, messages, and game results

$8–15

Breadboard

1

Allows circuit assembly without soldering

$5–10

Push Buttons

4

Used for the Start button and three reel stop buttons

$2–5

Green LED

1

Indicates a jackpot win

$0.25–1

Yellow LED

1

Indicates two matching symbols

$0.25–1

Red LED

1

Indicates a losing result

$0.25–1

Piezo Buzzer

1

Produces sound effects and win/lose tones

$1–3

330 Ω Resistors

3

Limits current to protect LEDs

Less than $1

Jumper Wires

20+

Connects all components together

$3–8

USB Cable

1

Powers and programs the Arduino Uno

$3–5

Estimated Total Cost


Approximately $38–77 CAD


The LCD display is one of the most vital components that you will need because it is the primary source for the user and slot machine. The screen displays a spinning animation, splash screen, jackpot/loss/two matches, and custom animations. The four push buttons are all extremely important as the enable the player to start the game and stop each reel in order.

The LED just gives us a visual display of the out come of the game and is optional. The green displays a jackpot, yellow display 2 matches or partial win, and the red indicates loss.

The buzzer is also optional and helps the player have the best possible experience which the production of sounds when there’s a loss or jackpot, and even when the reels are spinning.

Research

IMG_7048.jpeg
IMG_7047.jpeg

Before actually creating my game, I did thorough research on multiple different arduino tutorials character, explaining how to create custom, LCD displays, buttons, and game structure.

In my opinion, the Arduino LCD documentation was the most vital for me and helped me the most, which talked about how you should communicate with the display and position text using the cursor. I also looked at Arduino creatChar() documentation to deeply understand how the custom characters are stored and displayed on the lcd screen. This enabled me to animate the slot machine symbol such as stars, diamonds, cherries, etc.

resources:

https://docs.arduino.cc/learn/electronics/lcd-displays/

https://arduinogetstarted.com/tutorials/arduino-lcd-i2c

https://docs.arduino.cc/libraries/liquidcrystal/

https://www.arduinointro.com/articles/projects/create-custom-characters-for-the-i2c-lcd-easily


I also looked at many Arduino examples that involve buttons and the INPUT_PULLUP wiring. These specific examples built my understanding on how to read button presses without needing any external pull down resistors.

https://docs.arduino.cc/built-in-examples/digital/Button/

https://docs.arduino.cc/built-in-examples/digital/InputPullupSerial/


The most important function in my opinion was the randomSeed() function, I came across this whilst I was researching how to create random outcomes. This functions helped me create random reel values quicker and simpler to enhance the realistic aspect of this game.


https://docs.arduino.cc/language-reference/en/functions/random-numbers/random/

https://docs.arduino.cc/language-reference/en/functions/random-numbers/randomseed/


I made sure to do some more extra research on tutorials on buzzers, LEDs, and especially the LCD animations which were extremely important in the making of this game. I created a special spinning effect that’s not really spinning but looks like it is spinning and also created sound effects.

https://docs.arduino.cc/language-reference/en/functions/advanced-io/tone/




https://docs.sunfounder.com/projects/summary-of-fun-projects/en/latest/arduino/slot_machine.html

reviewed this game

Circuit Assembly

Circuit assembly

The slot machine circuit was design with the utilization of the arduino Uno and breadboard. I made sure to plan out how I am going to lay everything out on tinker cad first to make sure that the wires are all organized and it’s easier to troubleshoot. It was very vital that I kept my circuit as organized as possible as the project utilized multiple inputs and output devices at the same time.

The Arduino Uno is the central controller of the entire system. Every single component on the bread board needs to send its info to the Arduino or get instructions on what to do via code. The Arduino reads cutting inputs, creates a random value, constantly updates the lcd display with different animations, tells the leds when to turn on, and also create the sound via the buzzer.

Connection the lcd display

The first thing I connected to my bread board was the LCD display. The LCD display uses a specific I2C communication module, which is attached on the back of the LCD. One very big benefit of the I2C communication is that it decreases the amount of wires you need compared to a normal LCD display, which has a lot more data pins ( 6 or more) , whilst and I2C only requires 4.

VCC = power

GND = ground

SDA = connects to A4

SCL = connects to A5

The SDA and SCL allow text and custom graphics to be send to the display. After I wired to the LCD I coded it to display “Hello World” to test and to see if it works to prevent trouble shooting problems afterwards.


Resources Used


Arduino LCD Documentation

Arduino I2C LCD Tutorials

LiquidCrystal_I2C Library Documentation


Connecting the push buttons

1 start button

2 to stop reel 1

3 to stop reel 2

4 to stop reel 3

Each button was connected to any free pins and ground. Rather than using the basic external pull down resistors, the Arduino internal pull up resistors were enabled using the INPUT_PULLUP command.

This means when the pins are usually read high. When a button. Is press the pin tends to become connected directly to ground and reads low instead.

Using INPUT_PULLUP commands gives many benefits.

-less components needed for the creation of the project

-easier wiring

-more reliable

I made sure to test each button for individually to check if the presses are being detected efficiently.


Resources Used


Arduino Button Example

InputPullupSerial Example


Connecting the LEDs

The green LED displays that you got a jackpot.

Yellow LED displays that you got 2 matching animations.

Red LED displays that you lost and didn’t match any.

I made sure to connect each LED to a 330 ohm resistor. The makes sure to limit the amount of current flow going through each LED. If we didn’t use a resistor, high amount of current and damage your LEDs and potentially even your Arduino pin being used.


The positive leg (anode) which is the longer leg connects to the actual Arduino output pin and the shorter negative leg (cathode) connects to the ground via resistor.




Connect the buzzer

I made sure to connect my buzzer to the digital output pin through the positive side and the negative side to ground.

The buzz tends to revive signal waves that are created by the Arduino that are utilizing the tone() function in the code. Depending on the frequency you will get different sounds each time.

Short high frequency tones are specifically used when the reel is spinning. Longer notes are used when the outcome of the game is being displayed.

Final circuit testing

After I wired everything properly I made sure to check to see if each function of each component works.

After I made sure that every component works and my wiring is fine I then moved on.


Resources Used


Arduino tone() Documentation

Programming the Slot Machine

The code was separated into many different functions to make it easier to read and decrease the amount of repetition. I organized the program into multiple sections which made addressing errors easily.

Global variables

At the start of the code, I declared some global variables for the all the hardware components I was using and the game states.

PIN numbers for buttons, PIN numbers for LEDs, PIN numbers for buzzers , reel values, spin states, and animation variables.

Setup function

The setup() runs only once after the Arduino turns on.

Inside the setup()

The pin modes are configured

The LCD is initialized

The backlight is enabled

random value generator is seeded

The splash screen is displayed

The internal pull up resistors are enabled

One important line that many people don’t understand is the RandomSeed(analogRead(A0));

This uses electrical pulses from an analog pin that is not used to create random starting points for the random number generator.

If this is not implemented in the code the slot machine may just create the same order and sequence of animations every time you add power.

Splash screen

The showsplash() function shows us the games initial screen.

This functions clears the LCD and prints the statements “ SLOT MACHINE” and “press START”.

If you create a different function for the splash screen it helps enhance your code organization and helps the screen be reused whenever needed.

Resources Used


Arduino setup() Documentation

Arduino randomSeed() Documentation


Custom characters

I think the most difficult time I had in this project was creating the specific animations on the LCD.

The LCD only supports animations that are made from 5x8 pixel grid.

Each row of the pixels is then going to be stored as binary values.

The createChar() function uploads these patterns of the animation into the actual LCD’s character generator RAM which displays the characters allowing custom graphics to appear instead of just showing plain text.

Resources Used


Arduino createChar() Reference

LCD Custom Character Tutorials

https://docs.sunfounder.com/projects/summary-of-fun-projects/en/latest/arduino/slot_machine.html


LCD animations

I think the hardest programming features in this project were the LCD animations. The normal LCD can usually only display the built-in characters, so what I did was create custom animations via binary pixel patterns.

For example

B01110 represents a single row of pixels where the 1 means pixel on and the 0 means pixel off.

I combined 8 different rows together to complete one singular image. This technique was used to create the symbols.

The custom characters are then loaded into the LCD memory by using the variable lcd.createChar();

and displayed through the variable lcd.write();

Using the custom characters helped the machine look a lot more realistic instead of just using text.



Resources Used

Arduino createChar() Documentation: https://www.arduino.cc/reference/en/libraries/liquidcrystal/createchar/

LCD Custom Character Tutorial

LCD Character Generator Tools


LCD display Programming


I think one of the most important components that I used in this project was the 16 X2 I2C LCD display. The LCD is responsible for showing the slot machine symbol, splash screen, and Nguyen Messages as well as game results. But unlike any other LED which produces light directly, LCDs use something called liquid crystals to manipulate the light, and then display certain animations on the screen.


My screen contains 16 columns and two rows which allows me to display text and custom animations. In my code, I’ve used LCD functions a lot provided by the LiquidCrystal_I2C library.


For example

lcd.setCursor(0,0);

lcd.print(“SLOT MACHINE”);


The lcd.setCursor() function is what positions the symbols at a specific location on the display whilst the lcd.print() actually displays the symbols in the position. Other functions that were used a lot Include lcd.clear() which erases the screen, lcd.backlight() which displays the back light of the lcd, and lcd.write() which is used to display th custom animations.


Resources Used

Arduino LiquidCrystal Library Documentation: https://docs.arduino.cc/libraries/liquidcrystal/

Arduino LCD Tutorials

LiquidCrystal_I2C Library Examples



Starting the game

Once the user physically presses the start button, the program calls the start game() function. Disfunction is responsible for resetting the game and starting the spinning sequence illusion.

The primary thing this function does is to turn off all the LEDs that were on from the round before.

Next, there are three Boolean variables ( spin1, spin2, and spin3) that are all set to be true. This is because the variable is tracking if the reel is spinning or not.

spin1 = true;

spin2 = true;

spin3 = true;

If one of the variables is still true the reel will still keep spinning.



The main game loop

The spinning takes place in something called a while loop which I had no idea what it was until I researched.


while (spin1 || spin2 || spin3)


The double bars just mean or

This condition means that it will continue spinning if one reel is still spinning and the loop will only end when all three reels are stationary.

Using the while loop is very helpful when it come to the length of the game as it depends on players interacting. Instead of a for loop which only runs a specific amount of time, the whole loop can keep on looping until the specific condition becomes false making it a better and more efficient option for this project.

Resources Used


Arduino While Loop Documentation

Arduino Programming Structure Tutorials


Generating random reel values

During every single cycle of the loop, new random values are created for any reel that is still spinning.

if (spin1) reel1 = random(0,6);

if (spin2) reel2 = random(0,6);

if (spin3) reel3 = random(0,6);

The random function creates numbers from 0 to 5

defined each symbol as a number where:

0 is the skill

1 is the cherry

2 is the 777

3 is the bell

4 is the star

5 is the diamond

These values are frequently shifting while the reels are spinning.

The actual symbol only appears when each reel stops spinning and it lands on which ever value was stored in the moment.

Resources Used


Arduino random() Documentation


Creating reel animation

Real slot machines that use real reels that are rotating, because I have an LCD It is unable to physically rotate, so I decided to make a visual animation that mimics the spinning of a real slot machine.

I used to custom characters which were:

blurTop

blurBot

These characters created contained horizontal bars that would switch places very quickly, mimicking a spinning effect.

I did this by using a variable called toggle frame which keeps swigging between true and false.


toggleFrame = !toggleFrame;


As the LCD updates quickly the person playing the game thinks that it actually is spinning even as there are only 2 frames that are shown.

This technique is also very similar to many animations that are used in older games and cartoons, it works by creating an illusion.

This outcome is quite simple but it’s very effecting, as this effect makes the game look a lot more realistic.




Playing sound effects

tone(buzzer,1300,15);

I added sound effects to maximize the users engagement

A short high pitched click is repeatedly played which creates a similar noise to an actual slot machine. If I didn’t add sound effects I think the game would’ve not been as interesting as it was.


Resources Used


Arduino tone() Documentation



Detecting button presses

When the reels are still spinning the Arduino keeps checking the stop buttons to see if pressed.


if(digitalRead(reel1Btn)==LOW && spin1==true)


This statement looks at 2 conditions

  1. The button is currently pressed
  2. The reel is still spinning

If these conditions are true the reel will stop.

Using digitalRead() hells the Arduino look at the buttons a thousand times in a second.

As the INPUT_PULUP was used, a pressed button reads LOW instead of HIGH.

If you understand this inversion everything will be easy because this wa stage most vital lesson I learned during the creation of this game.


Resources Used


Arduino digitalRead() Documentation

InputPullupSerial Example



Displaying final symbol

When the reels are stationary the current value becomes permanent until it resets.


for example:


if(reel1 == 0)


It displayed the skull animation

The specific custom character is loaded using the LCD memory by the use of the creatChar() function. After the character is done loading it will be displayed on the screen. This takes place for every reel and it all happens very quick. The person playing the game can stop the reels in whatever sequence they wish to.



Delays and debouncing

Throughout this course I learned that push buttons have issues where they sometimes will create many signals when pressed. This is known as button bounce. To prevent this from happening you use a variable called delay.


delay(250);


This basically gives the button signal a break before continuing so it can recover.

Even though there are more advanced variations of debouncing this worked well for the slot machine I am trying to build.



Determining the outcome

After the reels have become stationary the program looks at the check result() function which compares the final reel values. There are 3 different possible outcomes.

If there is a jackpot

if(reel1 == reel2 && reel2 == reel3)

All three match


Partial win

else if(reel1 == reel2 ||

reel1 == reel3 ||

reel2 == reel3)

Exactly two reels are matching


Loss

If the other outcomes are not true then no symbols are matching.

With the use of conditional statements it helped the program look at every single possible outcome effectively.



Displaying results

Jackpot

  1. green LED turns on
  2. Victory song plays
  3. LCD continuously flashes
  4. “JACKPOT” text is displayed

Partial win

  1. the yellow LED turns on
  2. A medium pitched song starts playing
  3. “TWO MATCHES” is displayed

Loss

  1. Red LED is activated
  2. A low pitched song starts to play
  3. Displays “YOU LOSE!”



Resetting for the next game

After the results are displayed to the player the game then returns to the splash screen after a few seconds

The player can start a new game as soon as the splash screen is displayed without having to reset the Arduino as the game is in a loop

  1. Start the game
  2. Spin the reels
  3. Stop the reels
  4. Check to see the result
  5. Display the result
  6. Return back to the start screen

Downloads

Theory Behind the Project

This project looks at many different concepts that we learned in class that I applied to the creation of this game.

Digital inputs

Push buttons are a big example of input devices

Unlike the analog devices the digital inputs only have 2 states.

HIGH and LOW

the Arduino keeps checking these states through the variable digitalRead()

So whenever the button is pressed the Arduino will take action.

INPUT_PULLUP resistors

Normally the input pins need external resistors

Without these resistors the inputs may “float” between the HIGH and LOW

Floating inputs can create many random behaviours

The INPUT_PULLUP mode is the solution to this by making sure that it enable an internal resister inside the arduino.

Making sure that the pin stays at HIGH until the button is gonna be pressed.

Fewer components are needed, simpler wiring, and more reliable.

Digital outputs

LEDs and buzzer are digital outputs

The Arduino controls these outputs by using a variable called digitalWrite()

Outputs can either be HIGH which means on or LOW which means off.

These outputs help the Arduino communicate specific data to the user.

LEDs and current limiting

LEDs are known as light emitting diodes

A side only enables current to flow in one direction, if there is a lot of current being passed through it can potentially damage the LED, so for this reason you have to place 330 ohm resistors on the LED connecting to ground to the resistor can limit the amount of current going to the LED to help not damage the LED or the Arduino.

Buzzer

The buzzer can convert electrical signals that are received from the Arduino into real life sound waves. The Arduino creates frequencies using the variable tone()

Different frequencies will produce different types of notes.


Testing and Refinement

I think, testing and refinement were among the most significant parts of the creation of this game. Even as the initial concept of the slot machine looked very straightforward and simple, there were many obstacles that I had faced whilst the hardware assembly and software development. To solve these problems, I needed to troubleshoot experiment and even do multiple different rounds of testing.

Initial component testing

Before I assembled the entire game, I made sure to test each component first by itself. This really helped me in ensuring that every one of my device actually worked before going into the actual game.

I tested the LCD display by coding simple texts to display on the Arduino. This verified that I had placed the wiring correctly, the address was correct, and the communication between the display and the art we know was working without any flaws. When I was testing the game initially, the LCD displayed text correctly, which confirm that the wiring was correct and the library installation on the Arduino IDE worked.

After this, I made sure to test each push button one by one, by uploading a simple code I found online that displayed button states to the stereo monitor so I can check if it’s working properly. This helped me verify that every button was being detected by the yard. Do we know properly without any mistakes?. testing the buttons make sure I can prevent confusion in the future, when actually in putting them into my slot machine code.

I then made sure to test the LEDs by using random code I had found online. Each LED was connected one at a time to make sure that it works properly and to verify that the current limiting resistors were installed correctly.

By testing all these components one by one it decreased the chances off issues taking place later on.

LCD Character obstacles

I think what are the hardest challenges involved me actually creating the animations for the slot. Creating images that are actually recognizable by only using a 5X8 Pixel grid was a lot more difficult than I actually expected it to be.

The first version of the skull cherry and 777 looked very blurry and it definitely did not display clearly on the LCD, this is because the LCD has a limited resolution, so even what I made small changes to the binary pixel patterns, It really impacted how the animations are appearing.

To find a solution, I kept changing the pixel patterns and researched online over and over again got help from AI on how I could make it more visually appealing. After many tries, the symbol started to become more and more recognizable, but I had a better idea to make it even more recognizable, I made the symbol bigger so I can fit the screen fully so it looks a bit more high resolution.

I learned that engineering takes a lot of revisions and attempts before actually getting the result you were looking for.

Reel animation refinement

Creating the spinning effect was also another significant challenge I faced because the realtor was just displaying the changing symbols and I wanted to look like it’s spinning quicker. Even though it worked, it just looked very unrealistic, and they didn’t mimic an actual slot machine.

To make it look more interesting I experimented with different custom animation frames. I then created the blur bot and blur top characters to look like it was actually spinning.

I had to test many different delay values because if the delay value was very short, the animation would look very, very chaotic and not very visually appealing. If the delay was too long, the reels appeared very slow and definitely did not look like it was spinning.

After testing multiple different values, I picked a delay that looks more smooth and realistic.

This really improved the visual engagement for the player.

Buttons debouncing issue

When I was testing, I also discovered that when you press a reel stop button it would sometimes cause random behaviour. Like sometimes when I would press one button, it would be detected multiple different times.

This issue took place because the mechanical push buttons do not create perfectly clean signals. When you press the button, the context inside the button briefly balance, causing rapid transitions between high and low states.

To fix this problem, I added short delays where after every single button press, the delays will give the signal a break to actually stabilized before the game continues.

After plugging in this change, the real stopped much more consistently, and the gameplay started to become a lot more efficient.

User experience refinement

After I completed the base functions. I started to add extra things to enhance the users experience.

I made a lot more news, several little changes such as adding a splash screen, adding reel animations adding LED indicators, adding sound effects, improved when and loss messages, and even an LCD backlight flashing during jackpots.

Even as the changes were not extremely necessary for the functioning of this game, it still made the game look a lot more professional, and realistic.

Once all the futures were implemented, I needed to make sure that I tested the game multiple times to make sure that the buttons responded correctly real stopped independently. Random values changed properly symbols displayed correctly. LEDs activated correctly. Sound effects played correctly when conditions were evaluated correctly.


Final Result

IMG_7045.png

Finished product of the Arduino slot machine, successfully integrates electronics, programming, and player interaction a fun and interesting game. The final game uses the components such as the Arduino Uno, L2CI2C,4 push button buttons, buzzer, three LEDs.

Whenever the player presses the start button the real start to spin, due to the custom LCD animations I created to appear like the reels are removing while random values are constantly being created in the background. The player can stop each real and whatever order they want to independently by using the buttons. Making the game interactive just like an actual slot machine. When all reels have completely stopped, are we know checks the results and gives us audio and visual feedback through the sound effects LCD messages and LEDs.

I think one of the most successful parts of this project was how I used the custom LCD animation. These animations help me create a simple text display, which was my original idea into something that looks a lot more realistic, like an actual slot machine. As I added animations LEDs and sound effects, it made the game a lot more visually appealing, and interactively engaging.

Throughout the development process, I made sure to take a look at some of our previous lessons throughout this course and concepts I learned through throughout this semester such as the digital input and outputs random number generation, conditional statements, loops functions, and many troubleshooting techniques as well. The project also supported the importance of testing and refining an engineering design.

In conclusion, I think that I am really happy with this project because it achieved my original goal of making a fully functional realistic and engaging slot machine well also demonstrating many skills throughout the course. It not only achieved my original goal but also exceeded it. It displays an amazing example of how Arduino can be used to create electronics and programming into an interactive device that is not only educational but is also a lot of fun to play.

Downloads