Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe

Playing Snake Game using Raspberry Pi Game Pad- (Part 38/38)

By Ajish Alfred October 31, 2013

This article discusses about how to develop simple game pad hardware and interface it with the Raspberrypi board and also about the technique of interfacing a game code written in HTML5 with the game pad. Here a Snake game written in HTML5 and JavaScript is modified in such a way that it can be played with the new game pad having four push buttons. In this project the techniques of signals, pipe, fork etc. are used get the game running.

The Snake game running on a browser window forms the GUI or front end of the entire system. In a Linux operating system each hardware device is represented as a file. The device can be controlled by simply reading and writing into that file. The hardware of an operating system is on the one side and the user trying to access the hardware is on the other side, and in between them there might be several layers of process running which communicates each other using inter process communication methods. In this project there is game pad which is the hardware and there is a process which reads from the game pad and there is also a Pipe file or FIFO in-between the game and the game pad reading process.
[[wysiwyg_imageupload:11011:]]

 


 

The game runs in a browser window and it communicates with the game pad through a Named Pipe or FIFO. There are multiple processes running which can read from the game pad and write the required commands to the FIFO for controlling the game. The JavaScript written in the game code simply reads from the FIFO for the input control data.

Block Diagram of Raspberry pi gamepad

Fig. 2: Block Diagram Of Raspberry Pi Gamepad

The parent process here creates four child processes which are dedicated for each of the keys in the gamepad. Whenever a key is pressed or released, they will generate a signal and send it to the parent process with a value. Using this method the parent process can identify which key has been pressed or released. 
As soon as the parent process detects a key press from the value it received along with the signal, it simply writes a particular command value to the NAMED PIPE or FIFO. The HTML game will be reading continuously from the FIFO every 100ms and change the direction of the snake according to the command read.
The following part of the JavaScript reads from the file every 100ms and changes the direction of movement of the snake in the game.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
            function loadFile()
            {
                reader = new XMLHttpRequest() || new ActiveXObject(‘MSXML2.XMLHTTP’);
                reader.open(‘get’, ‘xyz’, true);
                reader.onreadystatechange = displayContents;     
                reader.send(null);
            }
 
            function displayContents()
            {
                ch = reader.responseText[0];
 
                if(ch == ‘l’)
                        heading = (heading == EAST) ? EAST : WEST;
                else if(ch == ‘r’)
                        heading = (heading == WEST) ? WEST : EAST;             
                else if(ch == ‘u’)
            heading = (heading == SOUTH) ? SOUTH : NORTH;
                else if(ch == ‘d’)
                        heading = (heading == NORTH) ? NORTH : SOUTH;
 
            }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
The functions used in the coding of the Gamepad code for writing operations on the FIFO are explained in the following section.
The FIFO needs to be created one using the following command in the same directory where the executable for the gamepad and the HTML game files exist.
mkfifo xyz
The FIFO can also be created using the code itself by adding the function mkfifo(), open()  as explained in a previous documentation.
The user can write data into the temporary file from the terminal itself using the ‘echo’ command as shown in the following example.
echo abcdef >> /tmp/my_fifo
The FIFO writing parent process is written in such a way that it will write commands to the FIFO in respond to the signals received from the child process. The commands that will be written to the FIFO for controlling the direction of the snake are listed below;
u -> Snake Upwards
d -> Snake Downwards
l -> Snake Left
r -> Snake RIght
These commands can be written into the FIFO with the help of the system() function.
system ( “echo r >> xyz );
The above function call will turn the Snake towards right.

Project Source Code

###

#include <bcm2835.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define IN_PIN1 RPI_GPIO_P1_07
#define IN_PIN2 RPI_GPIO_P1_22
#define IN_PIN3 RPI_GPIO_P1_18
#define IN_PIN4 RPI_GPIO_P1_16

#define OUT_PIN1 RPI_GPIO_P1_15
#define OUT_PIN2 RPI_V2_GPIO_P1_13
#define OUT_PIN3 RPI_GPIO_P1_12
#define OUT_PIN4 RPI_GPIO_P1_11

#define SNAKE_FIFO_NAME "xyz"

void set_pins_input ( void );
void set_pins_output ( void );
void set_output_pins_low ( void );
void button_signal_handler ( int sig, siginfo_t *siginfo, void *context );
void signal_on_state_change_pin1 ( void );
void signal_on_state_change_pin2 ( void );
void signal_on_state_change_pin3 ( void );
void signal_on_state_change_pin4 ( void );
void sig_set_handler ( int signo, void *handler );
void sig_send_val ( pid_t id, int signo, int val );

pid_t child_id [ 5 ];
int st = 0;

int main ( void )
{
int i;
int snake_fifo = -1;

if (!bcm2835_init())
return 1;

set_pins_output ();
set_output_pins_low ();
set_pins_input ();
delay ( 100 );

sig_set_handler ( SIGUSR1, &button_signal_handler );

if ( ! ( child_id [ 0 ] = fork () ) )
{
signal_on_state_change_pin1 ();
_exit ( 0 );
}
else;

if ( ! ( child_id [ 1 ] = fork () ) )
{
signal_on_state_change_pin2 ();
_exit ( 0 );
}
else;

if ( ! ( child_id [ 2 ] = fork () ) )
{
signal_on_state_change_pin3 ();
_exit ( 0 );
}
else;

if ( ! ( child_id [ 3 ] = fork () ) )
{
signal_on_state_change_pin4 ();
_exit ( 0 );
}
else;

while ( 1 )
{
system ( "echo x >> xyz" );
delay ( 100 );
}

bcm2835_close();
return 0;
}

void signal_on_state_change_pin1 ( void )
{
while ( 1 )
{
if ( bcm2835_gpio_lev ( IN_PIN1 ) )
{
delay ( 50 );
if ( bcm2835_gpio_lev ( IN_PIN1 ) )
{
sig_send_val ( getppid (), SIGUSR1, 1 );

do
{
while ( bcm2835_gpio_lev ( IN_PIN1 ) )
delay ( 1 );
delay ( 50 );
}
while ( bcm2835_gpio_lev ( IN_PIN1 ) );

sig_send_val ( getppid (), SIGUSR1, 1 );
}
else;
}else;
delay ( 1 );
}
}

void signal_on_state_change_pin2 ( void )
{
while ( 1 )
{
if ( bcm2835_gpio_lev ( IN_PIN2 ) )
{
delay ( 50 );
if ( bcm2835_gpio_lev ( IN_PIN2 ) )
{
sig_send_val ( getppid (), SIGUSR1, 2 );

do
{
while ( bcm2835_gpio_lev ( IN_PIN2 ) )
delay ( 1 );
delay ( 50 );
}
while ( bcm2835_gpio_lev ( IN_PIN2 ) );

sig_send_val ( getppid (), SIGUSR1, 2 );
}
else;
}else;
delay ( 1 );
}
}

void signal_on_state_change_pin3 ( void )
{
while ( 1 )
{
if ( bcm2835_gpio_lev ( IN_PIN3 ) )
{
delay ( 50 );
if ( bcm2835_gpio_lev ( IN_PIN3 ) )
{
sig_send_val ( getppid (), SIGUSR1, 3 );

do
{
while ( bcm2835_gpio_lev ( IN_PIN3 ) )
delay ( 1 );
delay ( 50 );
}
while ( bcm2835_gpio_lev ( IN_PIN3 ) );

sig_send_val ( getppid (), SIGUSR1, 3 );
}
else;
}else;
delay ( 1 );
}
}

void signal_on_state_change_pin4 ( void )
{
while ( 1 )
{
if ( bcm2835_gpio_lev ( IN_PIN4 ) )
{
delay ( 50 );
if ( bcm2835_gpio_lev ( IN_PIN4 ) )
{
sig_send_val ( getppid (), SIGUSR1, 4 );

do
{
while ( bcm2835_gpio_lev ( IN_PIN4 ) )
delay ( 1 );
delay ( 50 );
}
while ( bcm2835_gpio_lev ( IN_PIN4 ) );

sig_send_val ( getppid (), SIGUSR1, 4 );
}
else;
}else;
delay ( 1 );
}
}

void button_signal_handler ( int sig, siginfo_t *siginfo, void *context )
{
if ( 1 == *( ( int * ) &siginfo -> si_value ) )
system ( "echo u >> xyz" );
else if ( 2 == *( ( int * ) &siginfo -> si_value ) )
system ( "echo r >> xyz" );
else if ( 3 == *( ( int * ) &siginfo -> si_value ) )
system ( "echo l >> xyz" );
else if ( 4 == *( ( int * ) &siginfo -> si_value ) )
system ( "echo d >> xyz" );
else;

bcm2835_gpio_write ( OUT_PIN1, st );
st = ~ st;
}

void set_output_pins_low ( void )
{
bcm2835_gpio_write ( OUT_PIN1, LOW);
bcm2835_gpio_write ( OUT_PIN2, LOW);
bcm2835_gpio_write ( OUT_PIN3, LOW);
bcm2835_gpio_write ( OUT_PIN4, LOW);
}

void set_pins_output ( void )
{
bcm2835_gpio_fsel ( OUT_PIN1, BCM2835_GPIO_FSEL_OUTP );
bcm2835_gpio_fsel ( OUT_PIN2, BCM2835_GPIO_FSEL_OUTP );
bcm2835_gpio_fsel ( OUT_PIN3, BCM2835_GPIO_FSEL_OUTP );
bcm2835_gpio_fsel ( OUT_PIN4, BCM2835_GPIO_FSEL_OUTP );
}

void set_pins_input ( void )
{
bcm2835_gpio_fsel ( IN_PIN1, BCM2835_GPIO_FSEL_INPT );
bcm2835_gpio_set_pud ( IN_PIN1, BCM2835_GPIO_PUD_OFF );

bcm2835_gpio_fsel ( IN_PIN2, BCM2835_GPIO_FSEL_INPT );
bcm2835_gpio_set_pud ( IN_PIN2, BCM2835_GPIO_PUD_OFF );

bcm2835_gpio_fsel ( IN_PIN3, BCM2835_GPIO_FSEL_INPT );
bcm2835_gpio_fsel ( IN_PIN3, BCM2835_GPIO_FSEL_INPT );

bcm2835_gpio_set_pud ( IN_PIN4, BCM2835_GPIO_PUD_OFF );
bcm2835_gpio_set_pud ( IN_PIN4, BCM2835_GPIO_PUD_OFF );
}

void sig_send_msg ( pid_t id, int signo, char *msg )
{
union sigval *sigdata;

sigdata = malloc ( sizeof ( union sigval ) );
sigdata -> sival_ptr = msg;

sigqueue ( id, signo, *sigdata );

free ( sigdata );
}

void sig_send_val ( pid_t id, int signo, int val )
{
union sigval *sigdata;

sigdata = malloc ( sizeof ( union sigval ) );
sigdata -> sival_int = val;

sigqueue ( id, signo, *sigdata );

free ( sigdata );
}

void sig_set_handler ( int signo, void *handler )
{
struct sigaction *act;
act = malloc ( sizeof ( struct sigaction ) );
act -> sa_sigaction = handler;
act -> sa_flags = SA_SIGINFO;

sigaction ( signo, act, NULL );
}

 

###

 


Circuit Diagrams

Circuit-Diagram-For-Playing-Snake-Game-Raspberry-Pi

Project Video


Filed Under: Electronic Projects, Raspberry pi
Tagged With: game pad, Raspberry Pi, snake game
 

Next Article

← Previous Article
Next Article →

Questions related to this article?
👉Ask and discuss on Electro-Tech-Online.com and EDAboard.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

EE TECH TOOLBOX

“ee
Tech Toolbox: 5G Technology
This Tech Toolbox covers the basics of 5G technology plus a story about how engineers designed and built a prototype DSL router mostly from old cellphone parts. Download this first 5G/wired/wireless communications Tech Toolbox to learn more!

EE Learning Center

EE Learning Center
“engineers
EXPAND YOUR KNOWLEDGE AND STAY CONNECTED
Get the latest info on technologies, tools and strategies for EE professionals.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


RSS EDABOARD.com Discussions

  • How to simulate a microstrip gap with such a reference plane
  • Phase Shift Full Bridge suffers spurious FET turn_ON
  • optimum spacing between feed and sub reflector
  • Equipment to see if household should buy battery/solar/inverter?
  • 'HERIC' pairs of IGBTs essential for Mains inverters

RSS Electro-Tech-Online.com Discussions

  • Epson crystal oscillators
  • Adhesive Defibrillator Pad Cable
  • Simple LED Analog Clock Idea
  • Fun with AI and swordfish basic
  • Microinverters and storeage batteries?

Featured – LoRa/LoRaWan Series

  • What is the LoRaWAN network and how does it work?
  • Understanding LoRa architecture: nodes, gateways, and servers
  • Revolutionizing RF: LoRa applications and advantages
  • How to build a LoRa gateway using Raspberry Pi
  • How LoRa enables long-range communication
  • How communication works between two LoRa end-node devices

Recent Articles

  • How to design a heart-rate pulse sensor BPM meter
  • Three-phase EMI filter with neutral provides >1 MOhm insulation resistance
  • Infineon adds 60 V and 150 V power MOSFETs with 30 krad(Si) TID and AEC-Q101 qualification
  • Microchip releases DSC families with 78 ps PWM resolution and 40 Msps ADCs
  • Silanna Semiconductor releases laser driver IC with 86% efficiency

EE ENGINEERING TRAINING DAYS

engineering

Submit a Guest Post

submit a guest post
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • Battery Power Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • EV Engineering
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • Subscribe to our newsletter
  • About Us
  • Contact Us
  • Advertise

Copyright © 2025 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy

Search Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe