Difference between revisions of "F24: Tilt Maze"

From Embedded Systems Learning Academy
Jump to: navigation, search
(BILL OF MATERIALS)
(Implementation)
Line 363: Line 363:
 
===Implementation ===
 
===Implementation ===
 
* **LED Matrix Driver Functions**:
 
* **LED Matrix Driver Functions**:
**1. `matrix_init`: Initializes GPIO pins for the RGB LED matrix and sets up the synchronization mutex​:contentReference[oaicite:0]{index=0}.
+
* LED Matrix:  
**2. `display_update`: Refreshes the LED matrix display to reflect any changes​:contentReference[oaicite:1]{index=1}.
+
**1. Initialized LED matrix connected pins to board IOs.
**3. `display_clear`: Clears all active pixels on the matrix by setting them to zero​:contentReference[oaicite:2]{index=2}.
+
**2. Designed matrix driver for screen display by reading an matrix.
**4. `overwrite_pattern_to_screen`: Overwrites a specific pattern onto the LED matrix​:contentReference[oaicite:3]{index=3}.8
+
**3. Designed pause menu, main menu and gameplay environment for different states of game.
**5. `append_pattern_to_screen`: Adds a pattern to the existing screen matrix without overwriting​:contentReference[oaicite:4]{index=4}.
+
**4. Used GPIO pins as buttons as controls in main menu
 +
 
  
 
* **Accelerometer Driver**:
 
* **Accelerometer Driver**:
**1. `accelerometer_init`: Configures the ADXL345 accelerometer with ±2g sensitivity and sets up I2C communication with semaphores for thread safety​:contentReference[oaicite:5]{index=5}.
+
**1. `accelerometer_init`: Configures the ADXL345 accelerometer with ±2g sensitivity and sets up I2C communication with semaphores for thread safety
**2. `accelerometer_task`: Periodically reads acceleration data, applies smoothing, and updates player position based on tilt movements​:contentReference[oaicite:6]{index=6}.
+
**2. `accelerometer_task`: Periodically reads acceleration data, applies smoothing, and updates player position based on tilt movements
 +
 
 +
#include "accelerometer.h"
 +
#include "delay.h"
 +
#include "game_logic.h"
 +
#include "i2c.h"
 +
#include "maze.h"
 +
#include <stdio.h>
 +
 
 +
// Static variables for I2C semaphores
 +
static StaticSemaphore_t mutex_memory;
 +
static StaticSemaphore_t binary_sem_memory;
 +
 
 +
// Module variables
 +
volatile int8_t col_count = 32; // Start in middle
 +
volatile int8_t row_count = 32; // Start in middle
 +
volatile bool movement_enabled = false;
 +
SemaphoreHandle_t movement_mutex;
 +
 
 +
// Add acceleration smoothing
 +
static int16_t last_x = 0;
 +
static int16_t last_y = 0;
 +
const float smoothing_factor = 0.7f; // Increased for better responsiveness
 +
 
 +
void accelerometer_init(void) {
 +
  // Initialize I2C at 400kHz for faster response
 +
  i2c__initialize(I2C__2, 400 * 1000, 96 * 1000 * 1000UL, &binary_sem_memory, &mutex_memory);
 +
 
 +
  // Create mutex for thread-safe movement
 +
  movement_mutex = xSemaphoreCreateMutexStatic(&mutex_memory);
 +
 
 +
  // Configure ADXL345 accelerometer
 +
  i2c__write_single(I2C__2, ADXL345_WRITE, REG_DATA_FORMAT, 0x00); // ±2g range
 +
  i2c__write_single(I2C__2, ADXL345_WRITE, REG_POWER_CTL, 0x08);  // Measurement mode
 +
 
 +
  // Initialize smoothing variables
 +
  last_x = 0;
 +
  last_y = 0;
 +
}
 +
 
 +
void accelerometer_task(void *p) {
 +
  uint8_t data[6];
 +
  int new_x, new_y;
 +
  const TickType_t xFrequency = pdMS_TO_TICKS(50); // 40Hz sampling rate
 +
  TickType_t last_wake_time = xTaskGetTickCount();
 +
 
 +
  while (1) {
 +
    if (movement_enabled) {
 +
      // Read all 6 bytes of acceleration data
 +
      for (int i = 0; i < 6; i++) {
 +
        data[i] = i2c__read_single(I2C__2, ADXL345_WRITE, REG_DATAX0 + i);
 +
      }
 +
 
 +
      // Convert to 16-bit values
 +
      int16_t x = (int16_t)((data[1] << 8) | data[0]);
 +
      int16_t y = (int16_t)((data[3] << 8) | data[2]);
 +
 
 +
      // Apply smoothing
 +
      x = (int16_t)(smoothing_factor * x + (1.0f - smoothing_factor) * last_x);
 +
      y = (int16_t)(smoothing_factor * y + (1.0f - smoothing_factor) * last_y);
 +
 
 +
      last_x = x;
 +
      last_y = y;
 +
 
 +
      // Calculate new position using direct scaling
 +
      if (xSemaphoreTake(movement_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
 +
        // Calculate potential new position
 +
        new_x = col_count + (x / 75);
 +
        new_y = row_count - (y / 75); // Inverted Y axis
 +
 
 +
        // Check boundaries and wall collisions
 +
        if (new_x >= 0 && new_x < MATRIX_WIDTH && new_y >= 0 && new_y < MATRIX_HEIGHT) {
 +
 
 +
          // Check horizontal movement
 +
          if (new_x != col_count && !is_wall_at(current_level, new_x, row_count)) {
 +
            col_count = new_x;
 +
          }
 +
 
 +
          // Check vertical movement
 +
          if (new_y != row_count && !is_wall_at(current_level, col_count, new_y)) {
 +
            row_count = new_y;
 +
          }
 +
        }
 +
 
 +
        xSemaphoreGive(movement_mutex);
 +
      }
 +
    }
 +
 
 +
    // Use strict timing with vTaskDelayUntil
 +
    vTaskDelayUntil(&last_wake_time, xFrequency);
 +
  }
 +
}
 +
 
 +
void enable_movement(bool enable) {
 +
  if (xSemaphoreTake(movement_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
 +
    movement_enabled = enable;
 +
    // Reset smoothing when movement is enabled/disabled
 +
    last_x = 0;
 +
    last_y = 0;
 +
    printf("Movement %s\n", enable ? "enabled" : "disabled");
 +
    xSemaphoreGive(movement_mutex);
 +
  }
 +
}
  
 
* Maze Logic:
 
* Maze Logic:
**1. `get_maze_layout`: Retrieves the maze pattern for the current level&#8203;:contentReference[oaicite:7]{index=7}.
+
**1. `get_maze_layout`: Retrieves the maze pattern for the current level
**2. `is_wall_at`: Checks if a specific position in the maze contains a wall, used to constrain player movement&#8203;:contentReference[oaicite:8]{index=8}.
+
**2. `is_wall_at`: Checks if a specific position in the maze contains a wall, used to constrain player movement
**3. `is_goal_at`: Determines if the player has reached the maze's goal position to proceed to the next level&#8203;:contentReference[oaicite:9]{index=9}.
+
**3. `is_goal_at`: Determines if the player has reached the maze's goal position to proceed to the next level
 +
 
 +
#include "maze.h"
 +
#include <string.h>
 +
 
 +
// Static buffer for scaled patterns
 +
static uint8_t scaled_buffer[MAZE_FULL_SIZE * MAZE_FULL_SIZE];
 +
 
 +
// Add this helper function at the top of the file after includes
 +
static bool check_2x2_area(uint8_t level, uint8_t x, uint8_t y, uint8_t color_to_check) {
 +
  const uint8_t *maze = get_maze_layout(level);
 +
  if (!maze)
 +
    return false;
 +
 
 +
  // Check all 4 positions of 2x2 area
 +
  for (int dx = 0; dx < 2; dx++) {
 +
    for (int dy = 0; dy < 2; dy++) {
 +
      if (x + dx >= MAZE_FULL_SIZE || y + dy >= MAZE_FULL_SIZE)
 +
        continue;
 +
      if (maze[(y + dy) * MAZE_FULL_SIZE + (x + dx)] == color_to_check) {
 +
        return true;
 +
      }
 +
    }
 +
  }
 +
  return false;
 +
}
 +
 
 +
// Level information for all three levels
 +
static const level_info_t LEVEL_INFO[TOTAL_LEVELS] = {
 +
    {1, 1, 30, 30}, // Level 1: Start top-left, goal bottom-right
 +
    {1, 1, 30, 30}, // Level 2: Start top-left, goal bottom-right
 +
    {1, 1, 30, 30}  // Level 3: Start top-left, goal bottom-right
 +
};
 +
// Improved pattern scaling function with bounds checking
 +
static void scale_pattern(const uint8_t source[MAZE_SMALL_SIZE][MAZE_SMALL_SIZE]) {
 +
  for (uint8_t y = 0; y < MAZE_SMALL_SIZE; y++) {
 +
    for (uint8_t x = 0; x < MAZE_SMALL_SIZE; x++) {
 +
      uint8_t pixel = source[y][x];
 +
      // Scale each pixel to 2x2 in the output buffer
 +
      uint16_t dest_idx = (y * 2) * MAZE_FULL_SIZE + (x * 2);
 +
      scaled_buffer[dest_idx] = pixel;                      // Top left
 +
      scaled_buffer[dest_idx + 1] = pixel;                  // Top right
 +
      scaled_buffer[dest_idx + MAZE_FULL_SIZE] = pixel;    // Bottom left
 +
      scaled_buffer[dest_idx + MAZE_FULL_SIZE + 1] = pixel; // Bottom right
 +
    }
 +
  }
 +
}
 +
 
 +
// Replace existing is_wall_at function
 +
bool is_wall_at(uint8_t level, uint8_t x, uint8_t y) {
 +
  // Check out of bounds
 +
  if (x >= MAZE_FULL_SIZE - 1 || y >= MAZE_FULL_SIZE - 1) {
 +
    return true;
 +
  }
 +
 
 +
  // Check 2x2 area for walls
 +
  return check_2x2_area(level, x, y, COLOR_BLUE);
 +
}
 +
 
 +
// Replace existing is_trap_at function
 +
bool is_trap_at(uint8_t level, uint8_t x, uint8_t y) {
 +
  if (x >= MAZE_FULL_SIZE - 1 || y >= MAZE_FULL_SIZE - 1) {
 +
    return false;
 +
  }
 +
 
 +
  // Check 2x2 area for traps
 +
  return check_2x2_area(level, x, y, COLOR_YELLOW);
 +
}
 +
 
 +
// Replace existing is_goal_at function
 +
bool is_goal_at(uint8_t level, uint8_t x, uint8_t y) {
 +
  if (x >= MAZE_FULL_SIZE - 1 || y >= MAZE_FULL_SIZE - 1) {
 +
    return false;
 +
  }
 +
 
 +
  // Check 2x2 area for goal
 +
  return check_2x2_area(level, x, y, COLOR_GREEN);
 +
}
 +
 
 +
const uint8_t *get_maze_layout(uint8_t level) {
 +
  const uint8_t(*maze_pattern)[MAZE_SMALL_SIZE] = NULL;
 +
 
 +
  switch (level) {
 +
  case 0:
 +
    maze_pattern = LEVEL1_MAZE;
 +
    break;
 +
  case 1:
 +
    maze_pattern = LEVEL2_MAZE;
 +
    break;
 +
  case 2:
 +
    maze_pattern = LEVEL3_MAZE;
 +
    break;
 +
  default:
 +
    return NULL;
 +
  }
 +
 
 +
  scale_pattern(maze_pattern);
 +
  return scaled_buffer;
 +
}
 +
 
 +
// Pattern getter functions remain mostly unchanged but use new scaling
 +
const uint8_t *get_title_pattern(void) {
 +
  scale_pattern(TITLE_PATTERN);
 +
  return scaled_buffer;
 +
}
 +
 
 +
const uint8_t *get_you_win_pattern(void) {
 +
  scale_pattern(WIN_PATTERN);
 +
  return scaled_buffer;
 +
}
 +
 
 +
const uint8_t *get_game_over_pattern(void) {
 +
  scale_pattern(GAME_OVER_PATTERN);
 +
  return scaled_buffer;
 +
}
 +
 
 +
const uint8_t *get_level_up_pattern(uint8_t level) {
 +
  if (level < TOTAL_LEVELS) {
 +
    scale_pattern(LEVEL_UP_PATTERNS[level]);
 +
    return scaled_buffer;
 +
  }
 +
  return NULL;
 +
}
 +
 
 +
const level_info_t *get_level_info(uint8_t level) {
 +
  if (level < TOTAL_LEVELS) {
 +
    return &LEVEL_INFO[level];
 +
  }
 +
  return NULL;
 +
}
 +
 
 +
void get_start_position(uint8_t level, uint8_t *x, uint8_t *y) {
 +
  if (level < TOTAL_LEVELS && x && y) {
 +
    *x = LEVEL_INFO[level].start_x * 2; // Scale up for 64x64
 +
    *y = LEVEL_INFO[level].start_y * 2;
 +
  }
 +
}
 +
 
 +
void get_goal_position(uint8_t level, uint8_t *x, uint8_t *y) {
 +
  if (level < TOTAL_LEVELS && x && y) {
 +
    *x = LEVEL_INFO[level].goal_x * 2; // Scale up for 64x64
 +
    *y = LEVEL_INFO[level].goal_y * 2;
 +
  }
 +
}
  
 
* **Game Logic**:
 
* **Game Logic**:
**1. `set_player_to_start`: Resets the player position to the starting point of the current level&#8203;:contentReference[oaicite:10]{index=10}.
+
**1. set_player_to_start : Resets the player position to the starting point of the current level
**2. `handle_collisions`: Detects collisions with walls, traps, and goals, triggering state changes like `GAME_STATE_GAME_OVER` or `GAME_STATE_LEVEL_UP`&#8203;:contentReference[oaicite:11]{index=11}.
+
**2. handle_collisions: Detects collisions with walls, traps, and goals, triggering state changes like `GAME_STATE_GAME_OVER` or GAME_STATE_LEVEL_UP
**3. `change_game_state`: Manages game states such as `GAME_STATE_TITLE`, `GAME_STATE_PLAYING`, and `GAME_STATE_WIN`, and handles music transitions&#8203;:contentReference[oaicite:12]{index=12}.
+
**3. change_game_state: Manages game states such as `GAME_STATE_TITLE`, `GAME_STATE_PLAYING`, and `GAME_STATE_WIN`, and handles music transitions
 +
 
 +
switch (new_state) {
 +
  case GAME_STATE_TITLE:
 +
    stop_gameplay_music();
 +
    mp3_decoder__play_song_at_index(SOUND_TITLE);
 +
    enable_movement(false);
 +
    break;
 +
 
 +
  case GAME_STATE_PLAYING:
 +
    start_gameplay_music();
 +
    enable_movement(true);
 +
    break;
 +
 
 +
  case GAME_STATE_LEVEL_UP:
 +
    stop_gameplay_music();
 +
    mp3_decoder__play_song_at_index(SOUND_LEVELUP);
 +
    enable_movement(false);
 +
    break;
 +
 
 +
  case GAME_STATE_GAME_OVER:
 +
    stop_gameplay_music();
 +
    mp3_decoder__play_song_at_index(SOUND_LOSE);
 +
    enable_movement(false);
 +
    break;
 +
 
 +
  case GAME_STATE_WIN:
 +
    stop_gameplay_music();
 +
    mp3_decoder__play_song_at_index(SOUND_WIN);
 +
    enable_movement(false);
 +
    break;
 +
  }
 +
}
  
 
* **MP3 Decoder**:
 
* **MP3 Decoder**:
**1. `mp3_decoder__init`: Initializes the MP3 decoder, sets the default volume, and selects the storage device&#8203;:contentReference[oaicite:13]{index=13}.
+
**1. mp3_decoder__init: Initializes the MP3 decoder, sets the default volume, and selects the storage device
**2. `mp3_decoder__play_song_at_index`: Plays a specific song based on its index in single-cycle mode&#8203;:contentReference[oaicite:14]{index=14}.
+
**2. mp3_decoder__play_song_at_index: Plays a specific song based on its index in single-cycle mode
**3. `mp3_decoder__play_song_with_mode`: Allows playback in loop or single-cycle mode, depending on the game state&#8203;:contentReference[oaicite:15]{index=15}.
+
**3. mp3_decoder__play_song_with_mode: Allows playback in loop or single-cycle mode, depending on the game state
**4. `mp3_decoder__stop_playback`: Stops any active song playback&#8203;:contentReference[oaicite:16]{index=16}.
+
**4. mp3_decoder__stop_playback: Stops any active song playback
**5. `mp3_decoder__volume_set_level`: Adjusts the volume level of the MP3 decoder&#8203;:contentReference[oaicite:17]{index=17}.
+
**5. mp3_decoder__volume_set_level: Adjusts the volume level of the MP3 decoder
 +
 
 +
#pragma once
 +
 
 +
#include "gpio.h"
 +
#include "uart.h"
 +
#include <stdbool.h>
 +
#include <stdint.h>
 +
 
 +
typedef enum {
 +
  mp3_decoder__next_song = 0x01,
 +
  mp3_decoder__prev_song = 0x02,
 +
  mp3_decoder__play_at_index = 0x03,
 +
  mp3_decoder__play_loop = 0x08, // Added loop command
 +
  mp3_decoder__set_volume = 0x06,
 +
  mp3_decoder__select_device = 0x09,
 +
  mp3_decoder__reset = 0x0C,
 +
  mp3_decoder__stop = 0x16, // Added stop command
 +
} mp3_decoder__commands_e;
 +
 
 +
// Added playback mode enum
 +
typedef enum { MP3_PLAY_ONCE, MP3_PLAY_LOOP } mp3_playback_mode_t;
 +
 
 +
typedef struct {
 +
  uint8_t bytes[8];
 +
} mp3_decoder__command_t;
 +
 
 +
typedef union {
 +
  mp3_decoder__command_t mp3_decoder_command;
 +
  struct {
 +
    uint64_t start_byte : 8;
 +
    uint64_t version_byte : 8;
 +
    uint64_t data_length : 8;
 +
    uint64_t command_byte : 8;
 +
    uint64_t feedback_byte : 8;
 +
    uint64_t data_byte0 : 8;
 +
    uint64_t data_byte1 : 8;
 +
    uint64_t end_byte : 8;
 +
  } mp3_decoder_command_byte;
 +
} mp3_decoder__msg_t;
 +
 
 +
void mp3_decoder__init(void);
 +
void mp3_decoder__play_song_at_index(uint8_t index);
 +
void mp3_decoder__play_song_with_mode(uint8_t index, mp3_playback_mode_t mode);
 +
void mp3_decoder__stop_playback(void);
 +
void mp3_decoder__volume_set_level(uint8_t volume_level);
 +
void mp3_decoder__reset_decoder(void);
 +
bool mp3_decoder__is_playing(void);
  
 
== '''Testing & Technical Challenges''' ==
 
== '''Testing & Technical Challenges''' ==

Revision as of 22:13, 22 December 2024

Project Title

Tilt Maze

Tilt maze Logo

Abstract

Tilt Maze is a motion-controlled puzzle game that challenges players to navigate a luminous ball through procedurally generated mazes using device tilting mechanics. Players must reach the exit within time constraints while maneuvering around obstacles and collecting power-ups that provide temporary advantages. The game combines physical device control with strategic gameplay elements, offering high replayability through its randomized level design and emphasizing skills in balance, spatial reasoning, and quick decision-making.

Objectives & Introduction

The Tilt Maze Game combines hardware and software to create an interactive puzzle experience. It uses an ADXL345 accelerometer for tilt-based movement control, navigating a character through a maze displayed on a 64x64 LED matrix. FreeRTOS manages concurrent tasks like accelerometer input, display updates, and game logic, ensuring smooth and responsive gameplay. Game states, collision detection, and immersive audio feedback via an MP3 decoder enhance the experience. Semaphores and mutexes ensure thread-safe resource management, while debug outputs provide insights during development. This project demonstrates advanced integration of peripherals and real-time systems in a cohesive gaming application.

TEAM MEMBERS AND RESPONSIBILITIES

  • Shreya Belide
    • Developed code for MP3 Decoder Driver to play background music and sound effects.
    • Designed and implemented Game Architecture and State Machine logic.
    • Developed collision detection logic to ensure smooth player interactions.
    • Bug fixes in MP3 integration with FreeRTOS tasks.
    • Integrated subsystems including audio, display, and game logic.
    • Code Cleanup and Optimization.
    • Game Packaging and Presentation Preparation.
  • Jyoshna Mallineni
    • Developed Accelerometer Driver for tilt-based control.
    • Designed Maze Layouts and Game Graphics.
    • Implemented logic for dynamic player movement and boundary restrictions.
    • Developed and tested display rendering functions for the LED Matrix.
    • Debugged issues with accelerometer sensitivity and movement logic.
    • Assisted in subsystem integration and game logic testing.
    • Code Cleanup and Documentation.
  • Pavan Charith Devarapalli
    • Developed LED Matrix Driver for rendering the game visuals.
    • Implemented multi-level gameplay logic and player progression.
    • Designed logic for traps and goal conditions in the maze.
    • Integrated MP3 Decoder with SPI communication for audio playback.
    • Debugged synchronization issues between subsystems.
    • Tested and verified power supply stability for all components.
    • Assisted with subsystem integration and final game testing.
    • Managed Git Repository and Final Report Preparation.

Schedule

Week# Start Date End Date Task Status
1
  • 10/20/2024
  • 10/27/2024
  • 10/20/2024
  • 10/27/2024
  • Completed
  • Completed
2
  • 10/27/2024
  • 11/02/2024
  • Order necessary parts - LED Matrix , Speaker , Accelerometer
  • Completed
3
  • 11/02/2024
  • 11/08/2024
  • Read and familiarize with LED Matrix Datasheet
  • Completed
4
  • 11/02/2024
  • 11/08/2024
  • Develop graphics driver for LED matrix and implement initial game objects
  • Completed
5
  • 11/09/2024
  • 11/09/2024
  • 11/09/2024
  • 11/09/2024
  • 11/10/2024
  • 11/15/2024
  • 11/15/2024
  • 11/15/2024
  • Finalize wiki schedule
  • Order circuit boards components and complete the design for printing
  • circuit board and component assembly
  • Circuit board testing
  • Additional accessories if required and finalization of hardware
  • Completed
  • Completed
  • Completed
  • Completed
  • Completed
6
  • 11/16/2024
  • 11/22/2024
  • Integration of circuit boards and microcontroller
  • Game logic development
  • Testing and debugging the game logic
  • Completed
  • Completed
  • Completed
7
  • 11/23/2024
  • 11/29/2024
  • Integrate game logic code with LED matrix
  • Integrate game sounds with game logic
  • Completed
  • Completed
8
  • 11/30/2024
  • 12/06/2024
  • Integrate subsystem
  • Finalizing the video game
  • Update the wiki page.
  • Completed
  • Completed
  • Completed
9
  • 12/07/2024
  • 12/13/2024
  • Address bugs during testing of integrated system
  • Test pause/play functionality
  • Completed
  • Completed
  • Completed
10
  • 12/14/2024
  • 12/14/2024
  • 12/14/2024
  • 12/14/2024
  • 12/18/2024
  • 12/18/2024
  • 12/18/2024
  • 12/18/2024
  • Final Demo
  • Update Gitlab repo with final code.
  • Update test video.
  • Update the wiki page.
  • Progress
  • Progress
  • Progress
  • Progress


BILL OF MATERIALS

Part # Cost Source
SJ2 Board 1 $50.00 Preet
Sparkfun RGB (64x64) LED Matrix Display 1 $65.72 Amazon
Accelerometer 1 $10.99 Amazon
12v DC Power Jack Adapter Connector 1 $8.90 Amazon
MP3 Decoder 1 6.90 Amazon
Packaging 1 $12 Target
Jumper Wires 1 $6.99 Amazon
Total Cost $173.20

Design & Implementation

The design section can go over your hardware and software design. Organize this section using sub-sections that go over your design and implementation.

Hardware Design

Discuss your hardware design here. Show detailed schematics, and the interface here.

Hardware Interface

  • **LED Matrix Display**: 13 GPIO channels on SJ2 microcontroller
  • **Accelerometer (ADXL345)**: I2C communication on SJ2 microcontroller (SCL, SDA)
  • **MP3 Decoder**: SPI communication using MOSI, CS, SCK on SJ2 microcontroller
  • **Speaker**: AUX cord for audio output
  • **Power Supply**: 5V/4A adapter for powering the LED matrix and SJ2 microcontroller

Software Design

  • **LED Matrix:
    • 1. Initialized LED matrix connected pins to board IOs.
    • 2. Designed matrix driver for screen display by rendering maze patterns and player movements.
  • **Accelerometer**:
    • 1. Initialized I2C communication for ADXL345 accelerometer.
    • 2. Configured accelerometer in measurement mode and set sensitivity to ±2g.
    • 3. Processed tilt data to calculate real-time player movement commands.
  • **Mp3 Player**:
    • 1. Initialized using UART2.
    • 2. Set the device to the selected SD card and configured volume level.
    • 3. Played background music and sound effects based on game state.

RGB LED MATRIX

Hardware Interface

The 32x64 LED matrix is from Adafruit, with user mannual. It is composed of two upper and lower sectional LED pannels. Each pannel has R, G, B led channels and A, B, C, and D row control registers. Addtionally, column shift is controlled by Latch bit, clock is controled by CLK, and OE turns LED off when switching rows.

Connectivity Table LED Matrix to Sj2 Board:

RGB LED Matrix Pin Description SJ2 Board
R1 GPIO P1_14
G1 GPIO P4_29
B1 GPIO P0_7
R2 GPIO P0_9
G2 GPIO P0_25
B2 GPIO P1_30
A GPIO P1_23
B GPIO P1_29
C GPIO P2_4
D GPIO P2_6
CLK GPIO P2_8
LAT GPIO P0_17
OE GPIO P0_16
VCC 5VIN External Power Supply
GND GND On Board
LED Matrix Front
LED Matrix Rear

Implementation

  • **LED Matrix Driver Functions**:
  • LED Matrix:
    • 1. Initialized LED matrix connected pins to board IOs.
    • 2. Designed matrix driver for screen display by reading an matrix.
    • 3. Designed pause menu, main menu and gameplay environment for different states of game.
    • 4. Used GPIO pins as buttons as controls in main menu


  • **Accelerometer Driver**:
    • 1. `accelerometer_init`: Configures the ADXL345 accelerometer with ±2g sensitivity and sets up I2C communication with semaphores for thread safety
    • 2. `accelerometer_task`: Periodically reads acceleration data, applies smoothing, and updates player position based on tilt movements
  1. include "accelerometer.h"
  2. include "delay.h"
  3. include "game_logic.h"
  4. include "i2c.h"
  5. include "maze.h"
  6. include <stdio.h>

// Static variables for I2C semaphores static StaticSemaphore_t mutex_memory; static StaticSemaphore_t binary_sem_memory;

// Module variables volatile int8_t col_count = 32; // Start in middle volatile int8_t row_count = 32; // Start in middle volatile bool movement_enabled = false; SemaphoreHandle_t movement_mutex;

// Add acceleration smoothing static int16_t last_x = 0; static int16_t last_y = 0; const float smoothing_factor = 0.7f; // Increased for better responsiveness

void accelerometer_init(void) {

 // Initialize I2C at 400kHz for faster response
 i2c__initialize(I2C__2, 400 * 1000, 96 * 1000 * 1000UL, &binary_sem_memory, &mutex_memory);
 // Create mutex for thread-safe movement
 movement_mutex = xSemaphoreCreateMutexStatic(&mutex_memory);
 // Configure ADXL345 accelerometer
 i2c__write_single(I2C__2, ADXL345_WRITE, REG_DATA_FORMAT, 0x00); // ±2g range
 i2c__write_single(I2C__2, ADXL345_WRITE, REG_POWER_CTL, 0x08);   // Measurement mode
 // Initialize smoothing variables
 last_x = 0;
 last_y = 0;

}

void accelerometer_task(void *p) {

 uint8_t data[6];
 int new_x, new_y;
 const TickType_t xFrequency = pdMS_TO_TICKS(50); // 40Hz sampling rate
 TickType_t last_wake_time = xTaskGetTickCount();
 while (1) {
   if (movement_enabled) {
     // Read all 6 bytes of acceleration data
     for (int i = 0; i < 6; i++) {
       data[i] = i2c__read_single(I2C__2, ADXL345_WRITE, REG_DATAX0 + i);
     }
     // Convert to 16-bit values
     int16_t x = (int16_t)((data[1] << 8) | data[0]);
     int16_t y = (int16_t)((data[3] << 8) | data[2]);
     // Apply smoothing
     x = (int16_t)(smoothing_factor * x + (1.0f - smoothing_factor) * last_x);
     y = (int16_t)(smoothing_factor * y + (1.0f - smoothing_factor) * last_y);
     last_x = x;
     last_y = y;
     // Calculate new position using direct scaling
     if (xSemaphoreTake(movement_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
       // Calculate potential new position
       new_x = col_count + (x / 75);
       new_y = row_count - (y / 75); // Inverted Y axis
       // Check boundaries and wall collisions
       if (new_x >= 0 && new_x < MATRIX_WIDTH && new_y >= 0 && new_y < MATRIX_HEIGHT) {
         // Check horizontal movement
         if (new_x != col_count && !is_wall_at(current_level, new_x, row_count)) {
           col_count = new_x;
         }
         // Check vertical movement
         if (new_y != row_count && !is_wall_at(current_level, col_count, new_y)) {
           row_count = new_y;
         }
       }
       xSemaphoreGive(movement_mutex);
     }
   }
   // Use strict timing with vTaskDelayUntil
   vTaskDelayUntil(&last_wake_time, xFrequency);
 }

}

void enable_movement(bool enable) {

 if (xSemaphoreTake(movement_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
   movement_enabled = enable;
   // Reset smoothing when movement is enabled/disabled
   last_x = 0;
   last_y = 0;
   printf("Movement %s\n", enable ? "enabled" : "disabled");
   xSemaphoreGive(movement_mutex);
 }

}

  • Maze Logic:
    • 1. `get_maze_layout`: Retrieves the maze pattern for the current level
    • 2. `is_wall_at`: Checks if a specific position in the maze contains a wall, used to constrain player movement
    • 3. `is_goal_at`: Determines if the player has reached the maze's goal position to proceed to the next level
  1. include "maze.h"
  2. include <string.h>

// Static buffer for scaled patterns static uint8_t scaled_buffer[MAZE_FULL_SIZE * MAZE_FULL_SIZE];

// Add this helper function at the top of the file after includes static bool check_2x2_area(uint8_t level, uint8_t x, uint8_t y, uint8_t color_to_check) {

 const uint8_t *maze = get_maze_layout(level);
 if (!maze)
   return false;
 // Check all 4 positions of 2x2 area
 for (int dx = 0; dx < 2; dx++) {
   for (int dy = 0; dy < 2; dy++) {
     if (x + dx >= MAZE_FULL_SIZE || y + dy >= MAZE_FULL_SIZE)
       continue;
     if (maze[(y + dy) * MAZE_FULL_SIZE + (x + dx)] == color_to_check) {
       return true;
     }
   }
 }
 return false;

}

// Level information for all three levels static const level_info_t LEVEL_INFO[TOTAL_LEVELS] = {

   {1, 1, 30, 30}, // Level 1: Start top-left, goal bottom-right
   {1, 1, 30, 30}, // Level 2: Start top-left, goal bottom-right
   {1, 1, 30, 30}  // Level 3: Start top-left, goal bottom-right

}; // Improved pattern scaling function with bounds checking static void scale_pattern(const uint8_t source[MAZE_SMALL_SIZE][MAZE_SMALL_SIZE]) {

 for (uint8_t y = 0; y < MAZE_SMALL_SIZE; y++) {
   for (uint8_t x = 0; x < MAZE_SMALL_SIZE; x++) {
     uint8_t pixel = source[y][x];
     // Scale each pixel to 2x2 in the output buffer
     uint16_t dest_idx = (y * 2) * MAZE_FULL_SIZE + (x * 2);
     scaled_buffer[dest_idx] = pixel;                      // Top left
     scaled_buffer[dest_idx + 1] = pixel;                  // Top right
     scaled_buffer[dest_idx + MAZE_FULL_SIZE] = pixel;     // Bottom left
     scaled_buffer[dest_idx + MAZE_FULL_SIZE + 1] = pixel; // Bottom right
   }
 }

}

// Replace existing is_wall_at function bool is_wall_at(uint8_t level, uint8_t x, uint8_t y) {

 // Check out of bounds
 if (x >= MAZE_FULL_SIZE - 1 || y >= MAZE_FULL_SIZE - 1) {
   return true;
 }
 // Check 2x2 area for walls
 return check_2x2_area(level, x, y, COLOR_BLUE);

}

// Replace existing is_trap_at function bool is_trap_at(uint8_t level, uint8_t x, uint8_t y) {

 if (x >= MAZE_FULL_SIZE - 1 || y >= MAZE_FULL_SIZE - 1) {
   return false;
 }
 // Check 2x2 area for traps
 return check_2x2_area(level, x, y, COLOR_YELLOW);

}

// Replace existing is_goal_at function bool is_goal_at(uint8_t level, uint8_t x, uint8_t y) {

 if (x >= MAZE_FULL_SIZE - 1 || y >= MAZE_FULL_SIZE - 1) {
   return false;
 }
 // Check 2x2 area for goal
 return check_2x2_area(level, x, y, COLOR_GREEN);

}

const uint8_t *get_maze_layout(uint8_t level) {

 const uint8_t(*maze_pattern)[MAZE_SMALL_SIZE] = NULL;
 switch (level) {
 case 0:
   maze_pattern = LEVEL1_MAZE;
   break;
 case 1:
   maze_pattern = LEVEL2_MAZE;
   break;
 case 2:
   maze_pattern = LEVEL3_MAZE;
   break;
 default:
   return NULL;
 }
 scale_pattern(maze_pattern);
 return scaled_buffer;

}

// Pattern getter functions remain mostly unchanged but use new scaling const uint8_t *get_title_pattern(void) {

 scale_pattern(TITLE_PATTERN);
 return scaled_buffer;

}

const uint8_t *get_you_win_pattern(void) {

 scale_pattern(WIN_PATTERN);
 return scaled_buffer;

}

const uint8_t *get_game_over_pattern(void) {

 scale_pattern(GAME_OVER_PATTERN);
 return scaled_buffer;

}

const uint8_t *get_level_up_pattern(uint8_t level) {

 if (level < TOTAL_LEVELS) {
   scale_pattern(LEVEL_UP_PATTERNS[level]);
   return scaled_buffer;
 }
 return NULL;

}

const level_info_t *get_level_info(uint8_t level) {

 if (level < TOTAL_LEVELS) {
   return &LEVEL_INFO[level];
 }
 return NULL;

}

void get_start_position(uint8_t level, uint8_t *x, uint8_t *y) {

 if (level < TOTAL_LEVELS && x && y) {
   *x = LEVEL_INFO[level].start_x * 2; // Scale up for 64x64
   *y = LEVEL_INFO[level].start_y * 2;
 }

}

void get_goal_position(uint8_t level, uint8_t *x, uint8_t *y) {

 if (level < TOTAL_LEVELS && x && y) {
   *x = LEVEL_INFO[level].goal_x * 2; // Scale up for 64x64
   *y = LEVEL_INFO[level].goal_y * 2;
 }

}

  • **Game Logic**:
    • 1. set_player_to_start : Resets the player position to the starting point of the current level
    • 2. handle_collisions: Detects collisions with walls, traps, and goals, triggering state changes like `GAME_STATE_GAME_OVER` or GAME_STATE_LEVEL_UP
    • 3. change_game_state: Manages game states such as `GAME_STATE_TITLE`, `GAME_STATE_PLAYING`, and `GAME_STATE_WIN`, and handles music transitions

switch (new_state) {

 case GAME_STATE_TITLE:
   stop_gameplay_music();
   mp3_decoder__play_song_at_index(SOUND_TITLE);
   enable_movement(false);
   break;
 case GAME_STATE_PLAYING:
   start_gameplay_music();
   enable_movement(true);
   break;
 case GAME_STATE_LEVEL_UP:
   stop_gameplay_music();
   mp3_decoder__play_song_at_index(SOUND_LEVELUP);
   enable_movement(false);
   break;
 case GAME_STATE_GAME_OVER:
   stop_gameplay_music();
   mp3_decoder__play_song_at_index(SOUND_LOSE);
   enable_movement(false);
   break;
 case GAME_STATE_WIN:
   stop_gameplay_music();
   mp3_decoder__play_song_at_index(SOUND_WIN);
   enable_movement(false);
   break;
 }

}

  • **MP3 Decoder**:
    • 1. mp3_decoder__init: Initializes the MP3 decoder, sets the default volume, and selects the storage device
    • 2. mp3_decoder__play_song_at_index: Plays a specific song based on its index in single-cycle mode
    • 3. mp3_decoder__play_song_with_mode: Allows playback in loop or single-cycle mode, depending on the game state
    • 4. mp3_decoder__stop_playback: Stops any active song playback
    • 5. mp3_decoder__volume_set_level: Adjusts the volume level of the MP3 decoder
  1. pragma once
  1. include "gpio.h"
  2. include "uart.h"
  3. include <stdbool.h>
  4. include <stdint.h>

typedef enum {

 mp3_decoder__next_song = 0x01,
 mp3_decoder__prev_song = 0x02,
 mp3_decoder__play_at_index = 0x03,
 mp3_decoder__play_loop = 0x08, // Added loop command
 mp3_decoder__set_volume = 0x06,
 mp3_decoder__select_device = 0x09,
 mp3_decoder__reset = 0x0C,
 mp3_decoder__stop = 0x16, // Added stop command

} mp3_decoder__commands_e;

// Added playback mode enum typedef enum { MP3_PLAY_ONCE, MP3_PLAY_LOOP } mp3_playback_mode_t;

typedef struct {

 uint8_t bytes[8];

} mp3_decoder__command_t;

typedef union {

 mp3_decoder__command_t mp3_decoder_command;
 struct {
   uint64_t start_byte : 8;
   uint64_t version_byte : 8;
   uint64_t data_length : 8;
   uint64_t command_byte : 8;
   uint64_t feedback_byte : 8;
   uint64_t data_byte0 : 8;
   uint64_t data_byte1 : 8;
   uint64_t end_byte : 8;
 } mp3_decoder_command_byte;

} mp3_decoder__msg_t;

void mp3_decoder__init(void); void mp3_decoder__play_song_at_index(uint8_t index); void mp3_decoder__play_song_with_mode(uint8_t index, mp3_playback_mode_t mode); void mp3_decoder__stop_playback(void); void mp3_decoder__volume_set_level(uint8_t volume_level); void mp3_decoder__reset_decoder(void); bool mp3_decoder__is_playing(void);

Testing & Technical Challenges

The most challenging part of the Tilt Maze game was the integration and calibration of the accelerometer. Reading accurate tilt data and translating it into smooth, responsive movements for the game character required careful implementation. Additionally, ensuring the player's movement was constrained within the maze boundaries while avoiding unintended behavior added complexity.

Bug/Issue Name

Bug Number Description Solution
  • 1
  • Accelerometer readings were noisy and caused jittery player movement.
  • Implemented a weighted smoothing algorithm to filter out noise and ensure stable position updates.
  • 2
  • Player sometimes moved through walls due to rapid tilt changes.
  • Added collision detection checks at every update to ensure movements are blocked if a wall is detected in the new position.
  • 3
  • Accelerometer's orientation detection was inconsistent at certain tilt angles.
  • Calibrated the accelerometer and adjusted the thresholds for tilt detection to ensure reliable orientation changes.
  • 4
  • The game became unresponsive when the accelerometer task encountered delays.
  • Used FreeRTOS semaphores to synchronize accelerometer updates with game logic and ensured proper task prioritization.

Conclusion

Building the Tilt Maze game on a microcontroller proved to be a rewarding and challenging experience. Developing custom drivers for the accelerometer, LED matrix, and MP3 decoder required a deep understanding of embedded systems. Implementing FreeRTOS tasks to handle concurrent updates for accelerometer input, game logic, and display rendering added complexity but ensured smooth and responsive gameplay. One of the most challenging aspects was achieving accurate and stable accelerometer readings for tilt detection, which required calibration, noise filtering, and careful logic for player movement.

Throughout the project, we encountered various issues, including synchronization conflicts, noisy sensor data, and priority balancing in FreeRTOS. These challenges taught us the importance of debugging, modular design, and leveraging RTOS APIs effectively. As embedded engineers, we learned that creating a system from scratch involves meticulous attention to both hardware and software integration.

In the end, we successfully implemented a fun and interactive game that showcases the power of embedded systems. Future improvements could include adding a scoring system, dynamic maze generation, and more refined accelerometer controls to further enhance gameplay.

Project Video

[Watch the Tilt Maze game demo]

Project Source Code

https://gitlab.com/first892736/tilt-maze-group-2

References

Acknowledgement

Special thanks to Mr. Preet Kang for his lessons and detailed-documentation website on microcontrollers.

References Used

Appendix