Acrome-SMD Docs
All Acrome ProductsReferencesBlogCase StudiesContact Us
  • ACROME SMD
  • Electronics
    • 🔴SMD Red
      • Troubleshooting Guide
    • 🔵SMD Blue
    • 🟢SMD Green
    • Gateway Modules
      • Arduino Gateway Module
      • USB Gateway Module
    • Electrical Motors
      • Brushed DC Motors (BDC)
      • Stepper DC Motors (SDC)
      • Brushless DC Motor (BLDC)
      • Linear Actuator with Feedback – 75 lbs
    • Add-on Modules
      • Ambient Light Sensor Module
      • Button Module
      • Buzzer Module
      • IMU Module
      • Joystick Module
      • Potentiometer Module
      • Reflectance Sensor Module
      • RGB LED Module
      • Servo Module
      • Ultrasonic Distance Sensor Module
  • SMD Kits
    • Starter Kit
      • What You Can Build
    • Education Kit
      • What You Can Build
    • Motion Kit
      • What You Can Build
  • Software
    • Libraries
      • Python Library
      • Arduino Library
      • Java Library
      • Matlab Library
    • SMD UI
    • SMD Blockly
      • Introducing Customized Blockly Blocks
  • SMD Applications
    • Basics
      • Blink
      • Action - Reaction
      • Autonomous Lighting
      • Smart Doorbell
      • Security System
      • Distance Buzzer Warning
      • Distance Auto Stop
      • Smart Light Control
    • Interactive
      • Automatic Trash Bin
      • Radar
      • Chrome Dino Game Player
      • Play Chrome Dino Game With Joystick
      • Snake Game With Joystick
      • Pan-Tilt with Joystick Module
      • Joystick Mouse Control
      • Rev Up the Engine
      • Motor Rotation Based on Turn Input Value
      • Basic Motor Speed Control Application
      • Basic Motor Control Application Using PWM Input
      • Basic Motor Position Control Application
      • Basic Motor Torque Control Application
      • Motor Rotation Based on Joystick Counting
    • Robotics
      • Differential Robot Projects
      • Mouse Cursor Tracker Motion Robot
      • Waypoint tracker robot
      • Braitenberg Robot
      • Line-Follower Robot
      • Teleoperation Robot
      • Obstacle Avoidance Robot
      • ESP32 Wireless Controlled Mobile Robot
  • AI
    • Object Tracking Robot
    • Groq Chatbot-Controlled Robot
  • ROS
    • Teleoperation Robot with ROS
  • Mechanics
    • Building Set
      • Plates
        • 2x2 Plate Package
        • 2x3 120° Plate Package
        • 3x3 Plate Package
        • 3x5 Plate Package
        • 3x9 Plate Package
        • 11x19 Plate
        • 9x19 Plate
        • 5x19 Plate
        • 3x19 Plate
        • 9x11 Plate
        • 5x13 Plate
      • Joints
        • 60° Joint Package
        • 90° Joint Package
        • 120° Joint Package
        • Slot Joint M2 Package
        • Slot Joint M3 Package
        • U Joint Package
      • Mounts
        • Add-on Mount Package
        • Motor L Mount Package
        • Pan-Tilt Package
      • Wheels
        • Ball Wheel Package
        • Caster Wheel Package
        • Wheel Package
      • Cables
        • Power Cable 10 cm Package
        • Power Cable 20 cm Package
        • Power Cable 35 cm Package
        • RJ-11 Cable 7.5 cm Package
        • RJ-11 Cable 20 cm Package
        • RJ-11 Cable 35 cm Package
        • RJ-45 Cable 7.5 cm Package
        • RJ-45 Cable 20 cm Package
        • RJ-45 Cable 35 cm Package
      • Fasteners
        • M2x5 Allen Hex Screw Package
        • M3x6 Allen Hex Screw Package
        • M3x8 Allen Hex Screw Package
        • M3 Hex Nut Package
  • Help
    • Manual
    • Shops
    • Reach Us
Powered by GitBook
On this page
  • Step 1: Hardware & Software Overview
  • Step 2: Assemble
  • Step 3: Run & Test
  • Code
  1. SMD Applications
  2. Interactive

Play Chrome Dino Game With Joystick

PreviousChrome Dino Game PlayerNextSnake Game With Joystick

Last updated 1 month ago

This project allows users to control the Google Chrome Dino game using a connected through the platform. The is mapped to the jump and duck actions in the game. When the is pushed up, the game character jumps (using the spacebar key), and when the is pushed down, the character ducks (using the down arrow key).

About Tools and Materials:

()

()

()

Step 1: Hardware & Software Overview

Key Components:

  1. The platform acts as the communication hub, reading inputs and transmitting them to control the game. It collects data from the and processes it in real-time to translate movements into actions.

  2. The is used to control the actions in the Dino game. Vertical movements (up and down) control the character’s ability to jump and duck, with the acting as a physical input interface.

  3. GUI (Tkinter) The graphical user interface (GUI) provides real-time feedback to the user, showing the current state of the and the action being performed (jump or duck). This ensures transparency in how the movements are translated into game actions.

Project Key Features:

  1. Real-Time Control The allows the user to control the Dino character’s movements. Moving the up makes the Dino jump, while moving it down makes the Dino duck.

  2. Smooth Action Interpolation To make the movements smoother and more responsive, interpolation is applied to the values. This ensures the actions are triggered only when the movement crosses a certain threshold.

  3. Key State Management The system ensures that the keys (spacebar for jumping, down arrow for ducking) are held down or released at the appropriate times based on the input. This prevents unnecessary key presses and makes the actions more accurate.

  4. Graphical Feedback The GUI continuously displays the current X and Y values of the and the action being performed, providing visual feedback for the user to monitor their input.

Step 2: Assemble

Getting Started

  1. Hardware Setup

    • Make sure that the SMD is powered and all connections are correct

Project Wiring Diagram

Step 3: Run & Test

Code

import pyautogui
import tkinter as tk
import serial
from smd.red import Master, Red
from threading import Thread
import time
from serial.tools.list_ports import comports
from platform import system


# Serial Communication Settings
baudrate = 115200           # Baud rate for communication
module_id = 0               # ID of the SMD module
joystick_module_id = 5      # ID of the joystick module


# Joystick Thresholds
threshold = 0.10            # Minimum movement threshold for joystick activation
max_val = 100               # Maximum joystick value for normalization


# Dictionary to track key states
keys_state = {
    'space': False,         # Space key (jump action)
    'down': False           # Down arrow key (duck action)
}


def USB_Port():
    """
    Scans and identifies a compatible USB port for the current operating system.

    Returns:
        str: The detected USB port or None if no suitable port is found.
    """
    ports = list(comports())

    usb_names = {
        "Windows": ["USB Serial Port"],
        "Linux": ["/dev/ttyUSB"],
        "Darwin": [
            "/dev/tty.usbserial", "/dev/tty.usbmodem",
            "/dev/tty.SLAB_USBtoUART", "/dev/tty.wchusbserial",
            "/dev/cu.usbserial", "/dev/cu.usbmodem",
            "/dev/cu.SLAB_USBtoUART", "/dev/cu.wchusbserial",
        ]
    }

    os_name = system()
    print(f"Operating System: {os_name}")

    if ports:
        for port in ports:
            if any(name in port.device or name in port.description for name in usb_names.get(os_name, [])):
                print(f"USB device detected on port: {port.device}")
                return port.device
        print("No suitable USB device found. Available ports:")
        for port in ports:
            print(f"Port: {port.device}, Description: {port.description}, HWID: {port.hwid}")
    else:
        print("No ports detected!")
    return None


# Initialize the USB port and SMD module
SerialPort = USB_Port()
if not SerialPort:
    raise Exception("No compatible USB port found. Please check your connection.")

master = Master(SerialPort, baudrate)
master.attach(Red(module_id))
print("Connected Modules:", master.scan_modules(module_id))


# GUI Setup
root = tk.Tk()
root.title("Dino Game Controller")


# GUI Labels
joystick_label = tk.Label(root, text="Joystick State: (0, 0)", font=("Helvetica", 14))
joystick_label.pack(pady=10)

action_label = tk.Label(root, text="Action: None", font=("Helvetica", 14))
action_label.pack(pady=10)


def update_gui(x_val, y_val, action):
    """
    Updates the GUI to display the current joystick state and action.

    Args:
        x_val (float): The current x-axis value of the joystick.
        y_val (float): The current y-axis value of the joystick.
        action (str): The current action being performed (e.g., "Jump", "Duck", "None").
    """
    joystick_label.config(text=f"Joystick State: ({x_val:.2f}, {y_val:.2f})")
    action_label.config(text=f"Action: {action}")


def interpolate_value(value):
    """
    Normalizes joystick values and smooths movement.

    Args:
        value (float): The joystick input value.

    Returns:
        float: The interpolated value with smooth acceleration effect.
    """
    return (value / max_val) ** 2 * (1 if value > 0 else -1)


def joystick_control():
    """
    Continuously reads joystick data and translates movements into key presses.

    - Moves up (jump) when pushing joystick forward (Y > threshold).
    - Moves down (duck) when pulling joystick backward (Y < -threshold).
    - Releases keys when joystick is neutral.
    """
    action = "None"

    while True:
        joystick = master.get_joystick(module_id, joystick_module_id)

        if joystick is not None:
            x_val, y_val = joystick[0], joystick[1]
            y_val_smooth = interpolate_value(y_val)

            if abs(y_val_smooth) > threshold:
                # Jump (Up movement - Space key)
                if y_val_smooth > threshold:
                    if not keys_state['space']:
                        pyautogui.keyDown('space')
                        keys_state['space'] = True
                        action = "Jump"
                        update_gui(x_val, y_val, action)
                
                # Duck (Down movement - Down arrow key)
                elif y_val_smooth < -threshold:
                    if not keys_state['down']:
                        pyautogui.keyDown('down')
                        keys_state['down'] = True
                        action = "Duck"
                        update_gui(x_val, y_val, action)
            else:
                # Release keys if joystick is in neutral position
                if keys_state['space']:
                    pyautogui.keyUp('space')
                    keys_state['space'] = False
                    action = "None"
                
                if keys_state['down']:
                    pyautogui.keyUp('down')
                    keys_state['down'] = False
                    action = "None"

            # Update GUI
            update_gui(x_val, y_val, action)

        # Short delay to prevent excessive loop execution
        time.sleep(0.01)


# Start Joystick Control Thread
joystick_thread = Thread(target=joystick_control, daemon=True)
joystick_thread.start()

# Start GUI Main Loop
root.mainloop()

Connect the SMD to the PC or Arduino board using or .

Connect the to the SMD using an RJ-45 cable.

Joystick Input Monitoring: The system continuously reads the X and Y values. The Y-axis value is the primary input for controlling the jump and duck actions.

Jump and Duck Actions: When the is moved upward (beyond a threshold), the system simulates a key press of the spacebar to make the Dino jump. When moved downward, it presses the down arrow key to make the Dino duck.

Key Release Management: When the returns to its neutral position, the system releases any pressed keys (spacebar or down arrow) to reset the character’s action in the game.

GUI Updates: The GUI continuously updates with the latest values and the current action (jump, duck, or none), giving the user real-time feedback on their input and the corresponding actions in the game.

Conclusion: This project demonstrates how the platform can be used to create a joystick-controlled system for playing the Dino game. By integrating real-time input, smooth interpolation, and graphical feedback, the system offers a fun and interactive way to control the game.

joystick
ACROME SMD
joystick
joystick
joystick
SMD Red
Purchase Here
SMD USB Gateway
Purchase Here
Joystick Module
Purchase Here
ACROME SMD
ACROME SMD
joystick
joystick
Joystick Module
joystick
joystick
joystick
joystick
Joystick
joystick
joystick
joystick
joystick
joystick
joystick
joystick
USB Gateway Module
Arduino Gateway Module
Joystick Module
joystick's
joystick
joystick
joystick
ACROME SMD
joystick