Difference between revisions of "S15: Wizard's Chess System"

From Embedded Systems Learning Academy
Jump to: navigation, search
(Design & Implementation)
(Back-End)
 
(99 intermediate revisions by the same user not shown)
Line 1: Line 1:
=== Grading Criteria ===
+
== Wizard's Chess System ==
<font color="green">
+
[[File:S15_244_Grp17_harrypotter.gif|framed|boarder|text-top|]]
*  How well is Software & Hardware Design described?
+
[https://www.youtube.com/watch?v=IwjZ1J2b8UY&feature=youtu.be&t=42s Hermione Granger: "That's totally barbaric."]
*  How well can this report be used to reproduce this project?
 
*  Code Quality
 
*  Overall Report Quality:
 
**  Software Block Diagrams
 
**  Hardware Block Diagrams
 
**:  Schematic Quality
 
**  Quality of technical challenges and solutions adopted.
 
</font>
 
  
== Wizard's Chess System ==
+
Ron Weasley: "That's Wizard's chess."
  
 
== Abstract ==
 
== Abstract ==
The purpose of this project is to create an automated chessboard, displaying moves made by users playing chess. The web application server will be hosted on a Beaglebone Black.  Users log in and play a chess game hosted using Node.js. As moves are made on the web app,the pieces will be physically moved on the chessboard.
+
The purpose of this project is to create an automated chessboard, displaying moves made by users playing chess. The web application server will be hosted on a Beaglebone Black.  Users log in and play a chess game hosted using Node.js. As moves are made on the web app, the pieces will be physically moved on the chessboard.
  
 
== Objectives & Introduction ==
 
== Objectives & Introduction ==
Show list of your objectives.  This section includes the high level details of your project. You can write about the various sensors or peripherals you used to get your project completed.
+
The objective of this project is to have a physical chess game be carried out by the use of magnets. Users will input their move on a webpage which will be translated into movement of the chess pieces without human intervention, mimicking [http://harrypotter.wikia.com/wiki/Wizard%27s_Chess "Wizard's Chess"].
  
 
=== Team Members & Responsibilities ===
 
=== Team Members & Responsibilities ===
 
*  Yaron Alexandrovich
 
*  Yaron Alexandrovich
** Case Design, XY Plotter driver on SJOne Board, FreeRTOS Environment
+
** XY Plotter Construction, Electronic Hardware, Plotter Driver and Functions
 
*  Emil Kurian
 
*  Emil Kurian
** Case Design, XY Plotter driver on SJOne Board, FreeRTOS Environment
+
** XY Plotter Construction, Board Layout, Electromagnet
 
*  Gerard Ramos
 
*  Gerard Ramos
** Web Server, Case Design, Electromagnet, Chess Pieces
+
** Chess Pieces, Board Layout, Electromagnet
 
*  Fred Sun
 
*  Fred Sun
** Web Server, Case Design, Electromagnet, Chess Pieces
+
** Server-Side Software, FreeRTOS Environment, UART communication
  
 
== Schedule ==
 
== Schedule ==
Line 50: Line 42:
 
|4/26/2015
 
|4/26/2015
 
|Build casing and chessboard
 
|Build casing and chessboard
|In Progress
+
|Completed
 
|-
 
|-
 
|-
 
|-
Line 57: Line 49:
 
|4/19/2015
 
|4/19/2015
 
|Build/Control Electromagnet
 
|Build/Control Electromagnet
|In Progress
+
|Completed
 
|-
 
|-
 
|-
 
|-
Line 92: Line 84:
 
|4/26/2015
 
|4/26/2015
 
|3D print chess pieces + attach magnets to pieces
 
|3D print chess pieces + attach magnets to pieces
|In Progress
+
|Completed
 
|-
 
|-
 
|-
 
|-
Line 106: Line 98:
 
|5/3/2015
 
|5/3/2015
 
|Write functions for plotter to move chess pieces
 
|Write functions for plotter to move chess pieces
|In Progress
+
|Completed
 
|-
 
|-
 
|-
 
|-
Line 113: Line 105:
 
|5/10/2015
 
|5/10/2015
 
|Setup communication protocol between SJOne and Web Server
 
|Setup communication protocol between SJOne and Web Server
|In Progress
+
|Completed
 
|-
 
|-
 
|-
 
|-
Line 120: Line 112:
 
|5/17/2015
 
|5/17/2015
 
|FreeRTOS Environment
 
|FreeRTOS Environment
|In Progress
+
|Completed
 
|-
 
|-
 
|-
 
|-
Line 133: Line 125:
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
! scope="col"| #
 
 
! scope="col"| Item
 
! scope="col"| Item
 
! scope="col"| Cost  
 
! scope="col"| Cost  
Line 140: Line 131:
 
|-
 
|-
 
|-
 
|-
|1
+
|[http://www.makeblock.cc/xy-plotter-robot-kit-v2-0-with-electronic/ XY Plotter(With Electronics)]
|XY Plotter
 
 
|$300
 
|$300
 
|1
 
|1
Line 147: Line 137:
 
|-
 
|-
 
|-
 
|-
|2
+
|Wood Pieces
|Wood
 
 
|$10
 
|$10
 
|3
 
|3
Line 154: Line 143:
 
|-
 
|-
 
|-
 
|-
|3
+
|BeagleBone Black
|Polalu Stepper Drivers
+
|$60.00
|Please
+
|1
 +
|$60.00
 +
|-
 +
|-
 +
|SJOne Board
 +
|$80.00
 +
|1
 +
|$80.00
 +
|-
 +
|-
 +
|34 Pin Ribbon Cable
 +
|$3
 +
|1
 +
|$3
 +
|-
 +
|-
 +
|Pololu Stepper Drivers
 +
|$6
 +
|2
 +
|Free
 +
|-
 +
|-
 +
|100 uF Capacitors
 +
|$0.35
 
|2
 
|2
|Please
+
|Free
 +
|-
 +
|-
 +
|Break Away Pin Headers
 +
|$1.50/set
 +
|1
 +
|Free
 
|-
 
|-
 
|-
 
|-
|4
 
 
|Perfboard
 
|Perfboard
|.50
+
|$0.50
 
|2
 
|2
|$1.00
+
|$0.50, Free
 
|-
 
|-
 
|-
 
|-
|5
+
|RJ25 Pin Headers
|BeagleBone Black
+
|$0.50
|60
+
|4
 +
|$2.00
 +
|-
 +
|-
 +
|Electromagnet Core
 +
|???
 
|1
 
|1
|$60.00
+
|Free
 
|-
 
|-
 
|-
 
|-
 +
|Magnet Wires
 +
|$16.25
 +
|1 Roll
 +
|Free
 
|}
 
|}
  
 
== Design & Implementation ==
 
== Design & Implementation ==
 +
The chess game is hosted on a Beaglebone Black (BBB). The BBB is a open-source hardware single-board computer that runs an embedded Linux. The server back-end is powered by Node.JS, and ran as a local host such that any computer device can connect to it and play the game. As plays are made on the chess game, the changes in piece position are processed, and a string is transmitted over UART to the SJOne board. The SJOne interprets the string, and translates these to physical moves. By commanding the stepper motors and electromagnet, it moves chess pieces to reflect the changes made in game.
 +
 
=== Hardware Design ===
 
=== Hardware Design ===
The chess game is hosted on a Beaglebone Black (BBB). The BBB is a  open-source hardware single-board computer that runs an embedded Linux. The server back-end is powered by Node.JS, and ran as a local host such that any computer device can connect to it and play the game.  As plays are made on the chess game, the changes in piece position are processed, and a string is transmitted over UART to the SJOne board.  The SJOne interprets the string, and translates these to physical moves.  By commanding the stepper motors and electromagnet, it moves chess pieces to reflect the changes made in game.
+
====Hardware Interface====
 +
[[File:S15_244_Grp17_HardwareDiagram.jpg |frame|center| Hardware Interface Diagram. All components have common ground.]]
  
'''Hardware Interface'''
+
==== X-Y Plotter ====
 +
Initially, when looking for a solution for control on the XY plane, we looked for a pen plotter.  We found none.  After searching, we found an [http://www.makeblock.cc/xy-plotter-robot-kit-v2-0-with-electronic/ XY plotter kit by Makeblock].  The plotter has a usable area of 15" x 12", with each axis driven by a stepper motor.
  
[[File:S15_244_Grp17_HardwareDiagram.jpg |frame|center| Hardware Interface Diagram. All components have common ground.]]
 
 
'''XY Plotter Hardware'''
 
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
| [[File:S15_244_Grp17_FullBoard.jpg |thumb| center| XY Plotter with Board]]
 
 
| [[File:S15_244_Grp17_XYPlotterFull.jpg |thumb| center| Top View of XY Plotter]]
 
| [[File:S15_244_Grp17_XYPlotterFull.jpg |thumb| center| Top View of XY Plotter]]
 
| [[File:S15_244_Grp17_XYPlotterCloseUp.jpg|thumb| center| Close Up 1]]
 
| [[File:S15_244_Grp17_XYPlotterCloseUp.jpg|thumb| center| Close Up 1]]
Line 194: Line 220:
 
|}
 
|}
  
'''Computer Aided Design Chess Pieces'''
+
==== Chessboard ====
 +
The layout for the chessboard was designed in SolidWorks.  The design was then rastered onto a piece of wood with a laser cutter.  It has a playable grid of 11" x 11", with 2" graveyard at the bottom and top of the Y axis, and 1/2" margins at the left and right of the X axis.  This is to maximize the usable area of the XY plotter.
 +
 
 +
{| class="wikitable"
 +
|-
 +
| [[File:S15_244_Grp17_FullBoard.jpg |thumb| center| Chessboard Placement]]
 +
| [[File:S15_244_Grp17_Chesstop.jpg |thumb| center| Top View of Board]]
 +
|}
 +
 
 +
==== Computer Aided Design Chess Pieces ====
 +
Our chess pieces were 3d printed, one set blue and one set yellow (Spartan colors).  The pieces were designed significantly smaller than the chess board, such that a piece can slide over between squares, without disturbing other pieces.  We opened the bottom of the piece by melting the plastic with a soldering iron, and fixed a magnet and a washer to the inside of each peace.  This was to allow the electromagnet underneath to grip the piece. 
 +
 
 +
 
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
 
| [[File:S15_244_Grp17_ChessPieces.png |thumb| center| Chess Pieces for the Board]]
 
| [[File:S15_244_Grp17_ChessPieces.png |thumb| center| Chess Pieces for the Board]]
 +
| [[File:S15_244_Grp17_ChessPieces2.jpg |thumb| center| Actual Printed Pieces]]
 +
| [[File:S15_244_Grp17_ChessPieces3.jpg |thumb| center| Bottom with magnets]]
 
|}
 
|}
  
'''Electromagnet'''
+
==== Electromagnet ====
 +
An electromagnet is just a wire wound around a piece of metal.  To make ours, we used magnet wire, a thin wiring with very minimal insulation to allow magnetic fields to pass through.  We wrapped wire around a nail.  To lower the resistance of the wire, we wound 3 wires in parallel.  This gave us the same number of loops with less wire (less resistance) for the current to pass through.  The magnet was driven high by a 12 volt, 2 amp power source.  A relay was toggled on/off by the SJOne board, turning on/off the magnet.  The relay was protected by a flyback diode. 
 +
 
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
 
| [[File:S15_244_Grp17_Electromagnet.jpg |thumb| center| Electromagnet]]
 
| [[File:S15_244_Grp17_Electromagnet.jpg |thumb| center| Electromagnet]]
 
| [[File:S15_244_Grp17_Relay.jpg |thumb| center| Relay to Control when the electromagnet turns on and off]]
 
| [[File:S15_244_Grp17_Relay.jpg |thumb| center| Relay to Control when the electromagnet turns on and off]]
| [[File:S15_244_Grp17_Motor_Drivers.jpg |thumb| center| Custom Made Driver Motors for our board]]
 
 
|}
 
|}
'''Stepper Motor Driver'''
+
 
 +
==== Stepper Motor Driver ====
 +
Stepper motors work by having four electromagnets that magnetically grip a bar. By flipping these magnets on and off in a circular pattern, the bar rotates.
 +
 
 +
In order to use the stepper motors, 2 processes needed to occur. The first was setting the stepper motor driver. Our Drivers were the MD20B stepper motor drivers from Pololu, based on the DRV8825 IC from TI. In order to use these drivers, we had to manually set the step size (we chose an 1/8 step) and attach the power source we would be using. The logic was taken from the SJone, and the external power came from a 12V, 2A power supply.
 +
 
 +
To control the electromagnets at 1/8th step, a sine wave is passed through the electromagnets at a very specific rate. Feeding this sine wave too fast or too slow will fail to grip and step the stepper motor properly, so a perfectly calibrated feed rate is required. 
 +
 
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
Line 215: Line 263:
  
 
=== Software Design ===
 
=== Software Design ===
 +
==== Software Flowchart ====
 +
 +
[[File:S15_244_Grp17_Flowchart1.jpg |frame|center| High Level flowchart of the Software]]
 +
 +
==== Server-Side Software ====
 +
The code used for server-side can be viewed [https://github.com/fredthekid/chess here] (GitHub).
 +
 +
Note: If used on a BeagleBone Black, UART4 needs to be initialized.
 +
=====Front-End=====
 +
The front-end of the application was built using HTML, CSS, and JavaScript. The HTML was converted to Jade for readability. The front-end is comprised of 3 pages: Home, Play, and About. [http://getbootstrap.com/ Bootstrap by Twitter] was also used for it's nicely designed elements and ease of implementation. The graphical chessboard and its pieces was implemented in a JavaScript library called [http://chessboardjs.com/ chessboardjs]. It provided easy to use libraries to display the chessboard in the desired orientation.
 +
{| class="wikitable"
 +
|-
 +
| [[File:S15_244_Grp17_wchomepage.png |thumb| center| Home Page]]
 +
| [[File:S15_244_Grp17_chesswebpage.png |thumb| center| Play Page]]
 +
|}
 +
 +
=====Back-End=====
 +
Several frameworks were used when creating the back-end of the server. JavaScript was used because it allows everything on the server-side to be integrated together nicely without having to use multiple programming languages.
 +
 +
[https://nodejs.org/ Node.js] was used as the environment for the server-side application.
 +
 +
[http://expressjs.com/ Express.js] was used to hold all the middleware together.
 +
 +
[http://socket.io/ Socket.io] was used as the library to allow for real-time communication between web pages.
 +
 +
[https://github.com/jhlywa/chess.js Chess.js] is a JavaScript library that we used to make sure the moves made are valid.
  
=== Hosted Chess Game ===
+
[https://github.com/voodootikigod/node-serialport Node.js Serial Port] is a library that allows for communication to the SJOne Board via UART.
Our software was a two pronged approach: a website built from nodeJS and hosted on the BBB as well as a stepper motor control system implemented on the SJOne.
 
  
=== Stepper Motor Driver ===
+
When a user logs into the 'Play' page, socket.io will try and persist as many concurrent connections as possible. This allows for the real-time aspect. When the user makes a move a string will be sent to the SJOne Board via UART.
Stepper motors work by having four electromagnets that magnetically grip a bar. By flipping these magnets on and off in a circular pattern, the bar rotates. To control the magnets, we used Pololu amd20b drivers. These respond to a direction, and step signal.  On each rising edge of the direction signal, the motor steps a designated step size. We chose 1/8 step.
+
<syntaxhighlight lang="javascript">
 +
//Snippet of Server-side code
 +
//This is the packing of the UART String
 +
socket.on('clientUpdateRequest', function(data,last){
 +
currentfen = data;
 +
var lm = last;
 +
var cap = lm['captured'];
 +
socket.broadcast.emit('updateGameFromServer',currentfen);
 +
 +
if(cap == undefined) //no piece was captured, just a normal move
 +
{
 +
  //Move
 +
  ser.write('M');
 +
  ser.write(lm['from']);
 +
  ser.write(lm['to']);
 +
}
  
To control the electromagnets at 1/8th step, a sine wave is passed through the electromagnets at a very specific rate. Feeding this sine wave too fast or too slow will fail to grip and step the stepper motor properly, so a perfectly calibrated feed rate is required.   
+
else
 +
{
 +
  //Kill
 +
  ser.write('K');
 +
  ser.write(lm['captured']);
 +
  ser.write(lm['color']);
 +
  ser.write(lm['to']);
 +
     
 +
  //Move
 +
  ser.write('M');
 +
  ser.write(lm['from']);
 +
  ser.write(lm['to']);
 +
}
 +
});
 +
</syntaxhighlight>
 +
 
 +
When a move is made on the hosted chess game, the move is generated as a string and passed into the SJOne board via UART.  The string will be something like 'M','A','2','C','5'.  The first letter is the type of move it makes.  Either moving a piece, or killing a piece.  Then, positions two and three are the initial X and Y coordinates of the piece to move.  Positions 4 and 5 are the final X and Y coordinates of the piece to move.
 +
 
 +
==== Embedded Software ====
 +
 
 +
===== Tasks and Semaphores =====
 +
A FreeRTOS system was used to hold our system together. We used 2 tasks. One task was used at high priority (getFromBBB) to store UART strings into a character queue. This was set at high priority because the inputs coming from the web application should not be delayed, otherwise a string could be missed.
 +
 
 +
<syntaxhighlight lang="c">
 +
//Task 1, High Priority
 +
void getFromBBB(void* p)
 +
{
 +
    char uart_basket[6] = {};
 +
    while(1)
 +
    {
 +
        if(xSemaphoreTake(uart2InterruptSemaphore, portMAX_DELAY))
 +
        {
 +
            uart2Inst.gets(uart_basket,5,portMAX_DELAY);
 +
            if(xSemaphoreTake(chessMoveSemaphore, portMAX_DELAY))
 +
            {
 +
                for(int i = 0; i < 5; i++)
 +
                {
 +
                    xQueueSend(chessMoveQueue, uart_basket+i, portMAX_DELAY);
 +
                }
 +
                xSemaphoreGive(chessMoveSemaphore);
 +
            }
 +
        }
 +
    }
 +
}
 +
</syntaxhighlight>
 +
 
 +
The second task is for the plotter to move (chessMoveProcess). This is set at a lower priority. When there is is an item in the queue the task unblocks and the plotter is able to move. The semaphore used here is to only allow one task to access the chess queue at a time.
 +
 
 +
<syntaxhighlight lang="c">
 +
//Task 2, Medium Priority
 +
void chessMoveProcess(void* p)
 +
{
 +
    char currChar = '\0';
 +
    bool readyToMove = false;
 +
    uint8_t charCount = 0;
 +
    char uart_basket[6] = {};
 +
    while(1)
 +
    {
 +
        if(xSemaphoreTake(chessMoveSemaphore, portMAX_DELAY))
 +
        {
 +
            if(xQueueReceive(chessMoveQueue, &currChar, 0))
 +
            {
 +
                if(charCount == 4)
 +
                {
 +
                    uart_basket[4] = currChar;
 +
                    uart_basket[5] = '\0';
 +
                    readyToMove = true;
 +
                }
 +
                else
 +
                {
 +
                    uart_basket[charCount] = currChar;
 +
                    charCount++;
 +
                }
 +
            }
 +
            xSemaphoreGive(chessMoveSemaphore);
 +
        }
 +
 
 +
        if(readyToMove == true)
 +
        {
 +
            readyToMove = false;
 +
            charCount = 0;
 +
            //Move Functions Here
 +
        }
 +
}
 +
</syntaxhighlight>
 +
 
 +
===== UART =====
 +
The UART receive was done by using the pre-built drivers in the SJOne Package. We set the baud rate at 9600. The UART is set to interrupt when there is a character available. When the interrupt occurs a semaphore is given so that a task is unblocked.
 +
 
 +
<syntaxhighlight lang="c">
 +
//UART Interrupt
 +
void UART2_IRQHandler(void)
 +
{
 +
    uart2Inst.handleInterrupt();
 +
    xSemaphoreGiveFromISR(uart2InterruptSemaphore,NULL);
 +
}
 +
 
 +
//UART INIT
 +
Uart2& uart2Inst = Uart2::getInstance();
 +
uart2Inst.init(9600);
 +
isr_register(UART2_IRQn, UART2_IRQHandler);
 +
</syntaxhighlight>
 +
 
 +
===== Stepper Driver =====
 +
The code for the stepper driver can be viewed [https://github.com/fredthekid/sjonechess/blob/master/L5_Application/WizardChess.hpp here].
 +
 
 +
The XY plotter came with an Arduino and source code to power the plotter.  We ported the Arduino code over to the SJOne, modifying it to work on the SJOne platform.   
  
 
Our driver consisted of a series of helper functions, as well as three main functions:  
 
Our driver consisted of a series of helper functions, as well as three main functions:  
Line 235: Line 429:
 
dda_move is the move function.  This creates an x step and y step counter, then steps the x and y stepper motors until the counters are maxed out.  Then the x position and y position are updated.  
 
dda_move is the move function.  This creates an x step and y step counter, then steps the x and y stepper motors until the counters are maxed out.  Then the x position and y position are updated.  
  
Using the set_target, set_position, and dda_move, move routines to move the pieces were coded.  
+
Using the set_target, set_position, and dda_move, move routines to move the pieces were coded.
  
=== Move Routines ===
+
===== Move Routines =====
 +
The code for the move routines can be viewed [https://github.com/fredthekid/sjonechess/blob/master/L5_Application/WizardMove.hpp here].
  
 
moveToOrigin():        This moves the stepper motors to the origin.
 
moveToOrigin():        This moves the stepper motors to the origin.
Line 256: Line 451:
  
 
moveToGraveyardW():    Same, but for the white team's graveyard.
 
moveToGraveyardW():    Same, but for the white team's graveyard.
 
When a move is made on the hosted chess game, the move is generated as a string and passed into the SJOne board via UART.  The string will be something like [M][A][2][C][5].  The first letter is the type of move it makes.  Either moving a piece, or killing a piece.  Then, positions two and three are the initial X and Y coordinates of the piece to move.  Positions 4 and 5 are the final X and Y coordinates of the piece to move. 
 
  
 
Once a command comes in, for example a move command, it executes a series of move routines.  First, move to board buts the plotter in position [1][1].  Then, moveInGrid(initial X, inital Y) grips the piece to be moved.  Then moveToPassingLaneX and moveToPassingLaneY positions the piece to move around other chess pieces.  Then, moveInGrid(final X, same Y) is called to move to the proper X location.  Then, moveInGrid(same X, final Y) is called to move to the final Y position.  Then moveOffPassingLaneX and moveOffPassingLaneY centers the piece in its final resting location.  Finally, moveToOrign is called, moving the plotter to its resting position.
 
Once a command comes in, for example a move command, it executes a series of move routines.  First, move to board buts the plotter in position [1][1].  Then, moveInGrid(initial X, inital Y) grips the piece to be moved.  Then moveToPassingLaneX and moveToPassingLaneY positions the piece to move around other chess pieces.  Then, moveInGrid(final X, same Y) is called to move to the proper X location.  Then, moveInGrid(same X, final Y) is called to move to the final Y position.  Then moveOffPassingLaneX and moveOffPassingLaneY centers the piece in its final resting location.  Finally, moveToOrign is called, moving the plotter to its resting position.
  
 
=== Implementation ===
 
=== Implementation ===
This section includes implementation, but again, not the details, just the high level.  For example, you can list the steps it takes to communicate over a sensor, or the steps needed to write a page of memory onto SPI FlashYou can include sub-sections for each of your component implementation.
+
The chess game was implemented using Node.JS, hosted on a Beaglebone Black.  To access the game, any internet device would connect to the local Wifi hosting the BBB, and enter the local IP address of the BeagleBone Black into the address bar.   
  
The chess game was implemented using Node.JS, hosted on a Beaglebone Black.  To access the game, any internet device would connect to the local Wifi hosting the BBB, and enter the IP address into the address bar: 192.168.1.136:3030. 
+
The Chess game compiles itself into a 64 character long string, describing the entire board.  When a move is made, the change in positions are parsed out of the string, and a command is transmitted over UART to to the SJOne board.  The SJOne uses UART2 to receive the signal.  When a character comes in, an interrupt is thrown on the SJOne.  As characters come in, a string is appended with the received character, until \n is received.  Upon \n, the string is thrown into a queue.  
 
 
The Chess game compiles itself into a 64 character long string, describing the entire board.  When a move is made, the change in positions are parsed out of the string, and a command is transmitted over UART to to the SJOne board.  The SJOne uses UART2 to receive the signal.  When a character comes in, an interrupt is thrown on the SJOne.  As characters come in, a string is appended with the received character, until \n is received.  Upon \n, the string is thrown into a que.  
 
  
 
To service a string, the first character is examined.  Depending on that letter, the matching set of move routines are called.  The piece locations to be moved are parsed out of the string, and passed into the move routines, which include timed instructions to the stepper motors.   
 
To service a string, the first character is examined.  Depending on that letter, the matching set of move routines are called.  The piece locations to be moved are parsed out of the string, and passed into the move routines, which include timed instructions to the stepper motors.   
  
 
Therefore, the moves made in the chess game are physically expressed on the board.
 
Therefore, the moves made in the chess game are physically expressed on the board.
 
=== Chess Board ===
 
The chess board was created from an XY Plotter. The electromagnet was attached to the plotter, and would move under the chess board in order to pick up and move pieces. The Chess board itself was made from wood, and laser cut to our specification based on the usable size of the XY Plotter.  The plotter had a movable area of 11" X 15".  So we made the chess board 10 X 10, with 1/2" margins on the X plane.  2 inch graveyards were at Y = 0 and Y = Max.
 
 
=== Stepper Motors ===
 
In order to use the stepper motors, 2 processes needed to occur. The first was setting the stepper motor driver. Our Drivers were the MD20B stepper motor drivers from Pololu, based on the DRV8825 IC from TI. In order to use these drivers, we had to manually set the step size and attach the power source we would be using. The logic was taken from the SJone, and the external power came from a  12V, 2A power supply.
 
 
=== Electromagnet ===
 
After, we worked on the electromagnet. The magnet was handmade with the turns being wound by the team and power coming from an external 12-24V, 5A power source.
 
 
=== Data Conversion ===
 
Our game was hosed on the BBB, but our plotter was controlled by the SJone. In order to figure out where to move the pieces, a UART driver had to be created in order to pass data from the BBB to the SJone. The UART driver was interrupt based and would take in 5 characters at a time. These characters would then be deciphered and used to figure out the new chess piece locations.
 
 
Based on the location data for the pieces, the SJone would then engage the stepper motors and move them to the desired locations. This feat was accomplished by creating a software driver for the XY Plotter on the SJone board itself. The software driver was then used to create various move functions to be carried out based on the data coming in from the BBB.
 
 
=== Chess Pieces ===
 
Our Chess Pieces were 3d Printed and then modified for our use. The Modification was to add in a small magnet inside the chess piece and then weight the piece with a nut and washer on the bottom. These modifications allowed for the pieces to be grabbed by our electromagnet while staying stable and not getting attached to one another.
 
  
 
== Technical Challenges ==
 
== Technical Challenges ==
Line 298: Line 472:
 
=== Issue #3: Stepper Motor Calibration ===
 
=== Issue #3: Stepper Motor Calibration ===
 
The XY Plotter was purchased from MakeBlock. The kit included a portion of code to control the stepper motor. The code is originally written for the Arduino so it needed to ported over to the SJOne Board. However, once the code was ported over, there were several #defines and const variables on the Arduino side that did not match on the SJOne Board. We needed to calibrate the stepper so that it performs exactly how it does on the Arduino side.
 
The XY Plotter was purchased from MakeBlock. The kit included a portion of code to control the stepper motor. The code is originally written for the Arduino so it needed to ported over to the SJOne Board. However, once the code was ported over, there were several #defines and const variables on the Arduino side that did not match on the SJOne Board. We needed to calibrate the stepper so that it performs exactly how it does on the Arduino side.
 
=== Issue #4: Stepper Motor Timing===
 
Stepper motors have to be perfectly timed.  They store current flowing through them in a magnetic field, then a rising edge pulse switches the field from one electromagnet to the next.  This timing cycle needs to be perfect.  When FreeRTOS context switches the stepper motors are no longer receiving a current, and lose their magnetic fields.  Then, the context switch back to the stepper driver re-engergizes them. This causes unpredictable, uncontrolled behavior, and the stepper motors stutter and struggle to move.
 
  
 
== Conclusion ==
 
== Conclusion ==
We set out to create a Chess Board that could move the pieces by itself based on a game being played online. Instead, we created a potential fire hazard. After realizing that we created a potential fire hazard, we changed around a few things and instead created what was originally intended, a Wizard's Chess System. The Wizard's Chess possesses the ability to engage multiple players and move the pieces across the board via magnets underneath, suggesting to an errant watcher that the board indeed is magical.
 
 
As mentioned before, there were a few hiccups like the potential fire hazard. Testing and debugging the chess board was its own task because of the drivers we created from scratch. The motor drivers weren't as robust as we would have liked, wasting time and resources just to replace the driver over simple issues. Not to mention the testing that had to be done each phase such as how much power was going into each component or making sure that all the hardware was aligned in order to ensure that the precision we needed was there to play the game.
 
 
 
Overall, it would seem that a lot of effort went into creating a "over-the-top" version of a simple game. However, the chessboard we created draws from the various lessons learned though this class the and years we have been in engineering. A UART driver was implemented between two microcontrollers and ensured that the transmissions were read and properly processed. A driver was created for the XY Plotter from scratch, with all locations being mapped and programmed accordingly. An electromagnet was created, and though ultimately scrapped, it was successful in its intended purpose. FreeRTOS was used to prioritize the tasks of our board in order to ensure that all necessary functions were carried out properly and efficiently. By working on this project, the gap between knowledge attained in class and the actual implementation of these lessons was bridged.  
 
Overall, it would seem that a lot of effort went into creating a "over-the-top" version of a simple game. However, the chessboard we created draws from the various lessons learned though this class the and years we have been in engineering. A UART driver was implemented between two microcontrollers and ensured that the transmissions were read and properly processed. A driver was created for the XY Plotter from scratch, with all locations being mapped and programmed accordingly. An electromagnet was created, and though ultimately scrapped, it was successful in its intended purpose. FreeRTOS was used to prioritize the tasks of our board in order to ensure that all necessary functions were carried out properly and efficiently. By working on this project, the gap between knowledge attained in class and the actual implementation of these lessons was bridged.  
 
=== Project Video ===
 
Upload a video of your project and post the link here.
 
  
 
=== Project Source Code ===
 
=== Project Source Code ===
*  [https://sourceforge.net/projects/sjsu/files/CmpE_SJSU_S2015/ Sourceforge Source Code Link]
+
*  [https://github.com/fredthekid/sjonechess SJOne Chess Game Source Code]
 +
*  [https://github.com/fredthekid/chess BeagleBone Black Chess Game Source Code]
  
 
== References ==
 
== References ==
Line 321: Line 486:
 
Special thanks to Professor Peter Reischl.  He went out of his way to educate us on constructing the electromagnet.  Thanks for going out of your way to provide the knowledge and verification to construct our electromagnet.
 
Special thanks to Professor Peter Reischl.  He went out of his way to educate us on constructing the electromagnet.  Thanks for going out of your way to provide the knowledge and verification to construct our electromagnet.
  
=== References Used ===
+
Special thanks to Preetpal Kang.  His SJOne development platform and dedication to San Jose State University made this project possible.
List any references used in project.
+
 
 +
== Appendix ==  
 +
Instructable on how to control a stepper motor:
 +
http://www.instructables.com/id/How-to-use-a-Stepper-Motor/
  
=== Appendix ===
+
Assembly instructions for the linear plotter:
You can list the references you used.
+
http://learn.makeblock.cc/learn/resources/XY-plotter-V2.02-full-package/XY-Plotter-V2.02-Assembly-instructions.pdf

Latest revision as of 05:04, 11 February 2016

Wizard's Chess System

S15 244 Grp17 harrypotter.gif

Hermione Granger: "That's totally barbaric."

Ron Weasley: "That's Wizard's chess."

Abstract

The purpose of this project is to create an automated chessboard, displaying moves made by users playing chess. The web application server will be hosted on a Beaglebone Black. Users log in and play a chess game hosted using Node.js. As moves are made on the web app, the pieces will be physically moved on the chessboard.

Objectives & Introduction

The objective of this project is to have a physical chess game be carried out by the use of magnets. Users will input their move on a webpage which will be translated into movement of the chess pieces without human intervention, mimicking "Wizard's Chess".

Team Members & Responsibilities

  • Yaron Alexandrovich
    • XY Plotter Construction, Electronic Hardware, Plotter Driver and Functions
  • Emil Kurian
    • XY Plotter Construction, Board Layout, Electromagnet
  • Gerard Ramos
    • Chess Pieces, Board Layout, Electromagnet
  • Fred Sun
    • Server-Side Software, FreeRTOS Environment, UART communication

Schedule

Week Start Date End Date Task Status
1 3/27/2015 4/10/2015 Finish building XY Plotter Completed
2 4/12/2015 4/26/2015 Build casing and chessboard Completed
3 4/12/2015 4/19/2015 Build/Control Electromagnet Completed
4 4/12/2015 4/15/2015 Find/Buy appropriate magnets Completed
5 4/12/2015 4/19/2015 Write drivers for XY-Plotter Completed
6 4/12/2015 4/19/2015 Design web application GUI (Front-end) Completed
7 4/12/2015 4/26/2015 Host Web Server on Campus Completed
8 4/19/2015 4/26/2015 3D print chess pieces + attach magnets to pieces Completed
9 4/19/2015 5/3/2015 Develop Web Server Back-end Completed
10 4/26/2015 5/3/2015 Write functions for plotter to move chess pieces Completed
11 5/3/2015 5/10/2015 Setup communication protocol between SJOne and Web Server Completed
12 5/3/2015 5/17/2015 FreeRTOS Environment Completed
13 5/15/2015 5/23/2015 Debug, Debug, Debug In Progress

Parts List & Cost

Item Cost Quantity Total Cost
XY Plotter(With Electronics) $300 1 $300.00
Wood Pieces $10 3 $30.00
BeagleBone Black $60.00 1 $60.00
SJOne Board $80.00 1 $80.00
34 Pin Ribbon Cable $3 1 $3
Pololu Stepper Drivers $6 2 Free
100 uF Capacitors $0.35 2 Free
Break Away Pin Headers $1.50/set 1 Free
Perfboard $0.50 2 $0.50, Free
RJ25 Pin Headers $0.50 4 $2.00
Electromagnet Core ??? 1 Free
Magnet Wires $16.25 1 Roll Free

Design & Implementation

The chess game is hosted on a Beaglebone Black (BBB). The BBB is a open-source hardware single-board computer that runs an embedded Linux. The server back-end is powered by Node.JS, and ran as a local host such that any computer device can connect to it and play the game. As plays are made on the chess game, the changes in piece position are processed, and a string is transmitted over UART to the SJOne board. The SJOne interprets the string, and translates these to physical moves. By commanding the stepper motors and electromagnet, it moves chess pieces to reflect the changes made in game.

Hardware Design

Hardware Interface

Hardware Interface Diagram. All components have common ground.

X-Y Plotter

Initially, when looking for a solution for control on the XY plane, we looked for a pen plotter. We found none. After searching, we found an XY plotter kit by Makeblock. The plotter has a usable area of 15" x 12", with each axis driven by a stepper motor.

Top View of XY Plotter
Close Up 1
Close up 2

Chessboard

The layout for the chessboard was designed in SolidWorks. The design was then rastered onto a piece of wood with a laser cutter. It has a playable grid of 11" x 11", with 2" graveyard at the bottom and top of the Y axis, and 1/2" margins at the left and right of the X axis. This is to maximize the usable area of the XY plotter.

Chessboard Placement
Top View of Board

Computer Aided Design Chess Pieces

Our chess pieces were 3d printed, one set blue and one set yellow (Spartan colors). The pieces were designed significantly smaller than the chess board, such that a piece can slide over between squares, without disturbing other pieces. We opened the bottom of the piece by melting the plastic with a soldering iron, and fixed a magnet and a washer to the inside of each peace. This was to allow the electromagnet underneath to grip the piece.


Chess Pieces for the Board
Actual Printed Pieces
Bottom with magnets

Electromagnet

An electromagnet is just a wire wound around a piece of metal. To make ours, we used magnet wire, a thin wiring with very minimal insulation to allow magnetic fields to pass through. We wrapped wire around a nail. To lower the resistance of the wire, we wound 3 wires in parallel. This gave us the same number of loops with less wire (less resistance) for the current to pass through. The magnet was driven high by a 12 volt, 2 amp power source. A relay was toggled on/off by the SJOne board, turning on/off the magnet. The relay was protected by a flyback diode.

Electromagnet
Relay to Control when the electromagnet turns on and off

Stepper Motor Driver

Stepper motors work by having four electromagnets that magnetically grip a bar. By flipping these magnets on and off in a circular pattern, the bar rotates.

In order to use the stepper motors, 2 processes needed to occur. The first was setting the stepper motor driver. Our Drivers were the MD20B stepper motor drivers from Pololu, based on the DRV8825 IC from TI. In order to use these drivers, we had to manually set the step size (we chose an 1/8 step) and attach the power source we would be using. The logic was taken from the SJone, and the external power came from a 12V, 2A power supply.

To control the electromagnets at 1/8th step, a sine wave is passed through the electromagnets at a very specific rate. Feeding this sine wave too fast or too slow will fail to grip and step the stepper motor properly, so a perfectly calibrated feed rate is required.

Front
Back

Software Design

Software Flowchart

High Level flowchart of the Software

Server-Side Software

The code used for server-side can be viewed here (GitHub).

Note: If used on a BeagleBone Black, UART4 needs to be initialized.

Front-End

The front-end of the application was built using HTML, CSS, and JavaScript. The HTML was converted to Jade for readability. The front-end is comprised of 3 pages: Home, Play, and About. Bootstrap by Twitter was also used for it's nicely designed elements and ease of implementation. The graphical chessboard and its pieces was implemented in a JavaScript library called chessboardjs. It provided easy to use libraries to display the chessboard in the desired orientation.

Home Page
Play Page
Back-End

Several frameworks were used when creating the back-end of the server. JavaScript was used because it allows everything on the server-side to be integrated together nicely without having to use multiple programming languages.

Node.js was used as the environment for the server-side application.

Express.js was used to hold all the middleware together.

Socket.io was used as the library to allow for real-time communication between web pages.

Chess.js is a JavaScript library that we used to make sure the moves made are valid.

Node.js Serial Port is a library that allows for communication to the SJOne Board via UART.

When a user logs into the 'Play' page, socket.io will try and persist as many concurrent connections as possible. This allows for the real-time aspect. When the user makes a move a string will be sent to the SJOne Board via UART.

//Snippet of Server-side code
//This is the packing of the UART String
socket.on('clientUpdateRequest', function(data,last){
	currentfen = data;
	var lm = last;
	var cap = lm['captured'];
	socket.broadcast.emit('updateGameFromServer',currentfen);
	
	if(cap == undefined) //no piece was captured, just a normal move
	{
	  //Move
	  ser.write('M');
	  ser.write(lm['from']);
	  ser.write(lm['to']);
	}

	else
	{
	  //Kill
	  ser.write('K');
	  ser.write(lm['captured']);
	  ser.write(lm['color']);
	  ser.write(lm['to']);
       
	  //Move
	  ser.write('M');
	  ser.write(lm['from']);
	  ser.write(lm['to']);
	}
});

When a move is made on the hosted chess game, the move is generated as a string and passed into the SJOne board via UART. The string will be something like 'M','A','2','C','5'. The first letter is the type of move it makes. Either moving a piece, or killing a piece. Then, positions two and three are the initial X and Y coordinates of the piece to move. Positions 4 and 5 are the final X and Y coordinates of the piece to move.

Embedded Software

Tasks and Semaphores

A FreeRTOS system was used to hold our system together. We used 2 tasks. One task was used at high priority (getFromBBB) to store UART strings into a character queue. This was set at high priority because the inputs coming from the web application should not be delayed, otherwise a string could be missed.

//Task 1, High Priority
void getFromBBB(void* p)
{
    char uart_basket[6] = {};
    while(1)
    {
        if(xSemaphoreTake(uart2InterruptSemaphore, portMAX_DELAY))
        {
            uart2Inst.gets(uart_basket,5,portMAX_DELAY);
            if(xSemaphoreTake(chessMoveSemaphore, portMAX_DELAY))
            {
                for(int i = 0; i < 5; i++)
                {
                    xQueueSend(chessMoveQueue, uart_basket+i, portMAX_DELAY);
                }
                xSemaphoreGive(chessMoveSemaphore);
            }
        }
    }
}

The second task is for the plotter to move (chessMoveProcess). This is set at a lower priority. When there is is an item in the queue the task unblocks and the plotter is able to move. The semaphore used here is to only allow one task to access the chess queue at a time.

//Task 2, Medium Priority
void chessMoveProcess(void* p)
{
    char currChar = '\0';
    bool readyToMove = false;
    uint8_t charCount = 0;
    char uart_basket[6] = {};
    while(1)
    {
        if(xSemaphoreTake(chessMoveSemaphore, portMAX_DELAY))
        {
            if(xQueueReceive(chessMoveQueue, &currChar, 0))
            {
                if(charCount == 4)
                {
                    uart_basket[4] = currChar;
                    uart_basket[5] = '\0';
                    readyToMove = true;
                }
                else
                {
                    uart_basket[charCount] = currChar;
                    charCount++;
                }
            }
            xSemaphoreGive(chessMoveSemaphore);
        }

        if(readyToMove == true)
        {
            readyToMove = false;
            charCount = 0;
            //Move Functions Here
        }
}
UART

The UART receive was done by using the pre-built drivers in the SJOne Package. We set the baud rate at 9600. The UART is set to interrupt when there is a character available. When the interrupt occurs a semaphore is given so that a task is unblocked.

//UART Interrupt
void UART2_IRQHandler(void)
{
    uart2Inst.handleInterrupt();
    xSemaphoreGiveFromISR(uart2InterruptSemaphore,NULL);
}

//UART INIT
Uart2& uart2Inst = Uart2::getInstance();
uart2Inst.init(9600);
isr_register(UART2_IRQn, UART2_IRQHandler);
Stepper Driver

The code for the stepper driver can be viewed here.

The XY plotter came with an Arduino and source code to power the plotter. We ported the Arduino code over to the SJOne, modifying it to work on the SJOne platform.

Our driver consisted of a series of helper functions, as well as three main functions: set_position(x position, y position) set_target(x target, y target) dda_move(feedrate)

x position and y position are NOT tick locations. These represent physical locations in the X and Y grid. The helper functions convert these into number of ticks. The feedrate is the speed at which the sine wave is pulsed through the stepper motor to achieve 1/8th step twitches.

set_position stores a positional value that the plotter is currently at. set_target stores a value that the stepper motor wants to achieve. Then the number of steps for x and y to achieve this position are calculated. dda_move is the move function. This creates an x step and y step counter, then steps the x and y stepper motors until the counters are maxed out. Then the x position and y position are updated.

Using the set_target, set_position, and dda_move, move routines to move the pieces were coded.

Move Routines

The code for the move routines can be viewed here.

moveToOrigin(): This moves the stepper motors to the origin.

moveToBoard(): This moves the stepper motors to the first square on the 8x8 chess board.

moveInGrid(x, y): This moves the stepper motors to the designated x and y position of the 8x8 chess board.

moveToPassingLaneX(): This moves a chess piece off the center of the square, so that it can navigate around other pieces.

moveToPassingLaneY(): Same, but for y-axis.

moveOffPassingLaneX(): Returns piece to center of grid from x-axis passing lane.

moveOffPassingLaneY(): Returns from y-axis passing lane.

moveToGraveyardB(): Once a piece is gripped, it moves that piece into the x passing lane, than carries it to its graveyard.

moveToGraveyardW(): Same, but for the white team's graveyard.

Once a command comes in, for example a move command, it executes a series of move routines. First, move to board buts the plotter in position [1][1]. Then, moveInGrid(initial X, inital Y) grips the piece to be moved. Then moveToPassingLaneX and moveToPassingLaneY positions the piece to move around other chess pieces. Then, moveInGrid(final X, same Y) is called to move to the proper X location. Then, moveInGrid(same X, final Y) is called to move to the final Y position. Then moveOffPassingLaneX and moveOffPassingLaneY centers the piece in its final resting location. Finally, moveToOrign is called, moving the plotter to its resting position.

Implementation

The chess game was implemented using Node.JS, hosted on a Beaglebone Black. To access the game, any internet device would connect to the local Wifi hosting the BBB, and enter the local IP address of the BeagleBone Black into the address bar.

The Chess game compiles itself into a 64 character long string, describing the entire board. When a move is made, the change in positions are parsed out of the string, and a command is transmitted over UART to to the SJOne board. The SJOne uses UART2 to receive the signal. When a character comes in, an interrupt is thrown on the SJOne. As characters come in, a string is appended with the received character, until \n is received. Upon \n, the string is thrown into a queue.

To service a string, the first character is examined. Depending on that letter, the matching set of move routines are called. The piece locations to be moved are parsed out of the string, and passed into the move routines, which include timed instructions to the stepper motors.

Therefore, the moves made in the chess game are physically expressed on the board.

Technical Challenges

Issue #1: Stepper Motor Drivers

As current flows into a stepper motor, it stores this energy in magnetic fields. The reverse is true. That is, when current is no longer supplied to the motor, the magnetic field collapses creating current, known as back EMF. The stepper motor drivers contain circuitry to protect itself from this back EMF. However, adjusting the current setting or unplugging the stepper motor driver while engaged WILL damage the driver.

Issue #2: Electromagnet

One of the other issues we encountered was with safety regarding the electromagnet, mainly due to heat, one of the things we wanted to calculate was how much current to run through the electromagnet in order to start moving pieces. As we were doing our test, the way that the electromagnet moved under the board scraped little pieces of wood on it. After a couple of minutes of testing we noticed smoke coming from the bottom of the board, at first we thought it was the electromagnet heating up the board way too much but actually the issue was the the little pieces of wood was going on the electromagnet, and due to the high amount of heat this caused the wooden dust to burn. After noticing this fire hazard we decided to not use the electromagnet anymore because it wasn't worth the risk if anything catching on fire.

Issue #3: Stepper Motor Calibration

The XY Plotter was purchased from MakeBlock. The kit included a portion of code to control the stepper motor. The code is originally written for the Arduino so it needed to ported over to the SJOne Board. However, once the code was ported over, there were several #defines and const variables on the Arduino side that did not match on the SJOne Board. We needed to calibrate the stepper so that it performs exactly how it does on the Arduino side.

Conclusion

Overall, it would seem that a lot of effort went into creating a "over-the-top" version of a simple game. However, the chessboard we created draws from the various lessons learned though this class the and years we have been in engineering. A UART driver was implemented between two microcontrollers and ensured that the transmissions were read and properly processed. A driver was created for the XY Plotter from scratch, with all locations being mapped and programmed accordingly. An electromagnet was created, and though ultimately scrapped, it was successful in its intended purpose. FreeRTOS was used to prioritize the tasks of our board in order to ensure that all necessary functions were carried out properly and efficiently. By working on this project, the gap between knowledge attained in class and the actual implementation of these lessons was bridged.

Project Source Code

References

Acknowledgement

Special thanks to Hugo Quiroz. He provided mechanical knowledge, access to laboratory and equipment, and dedication to our project. Thanks for the measures, cuts, materials, and laser cutter to etch our chess board.

Special thanks to Professor Peter Reischl. He went out of his way to educate us on constructing the electromagnet. Thanks for going out of your way to provide the knowledge and verification to construct our electromagnet.

Special thanks to Preetpal Kang. His SJOne development platform and dedication to San Jose State University made this project possible.

Appendix

Instructable on how to control a stepper motor:

http://www.instructables.com/id/How-to-use-a-Stepper-Motor/

Assembly instructions for the linear plotter:

http://learn.makeblock.cc/learn/resources/XY-plotter-V2.02-full-package/XY-Plotter-V2.02-Assembly-instructions.pdf