• No results found

JOAKIM ERICSONADAM WESTERMARK Remote Arduino powered chess CheckMate

N/A
N/A
Protected

Academic year: 2022

Share "JOAKIM ERICSONADAM WESTERMARK Remote Arduino powered chess CheckMate"

Copied!
74
0
0

Loading.... (view fulltext now)

Full text

(1)

IN

DEGREE PROJECT TECHNOLOGY, FIRST CYCLE, 15 CREDITS

STOCKHOLM SWEDEN 2020 ,

CheckMate

Remote Arduino powered chess JOAKIM ERICSON

ADAM WESTERMARK

(2)
(3)

CheckMate

Remote Arduino powered chess

JOAKIM ERICSON ADAM WESTERMARK

Bachelor’s Thesis at ITM Supervisor: Nihad Subasic

Examiner: Nihad Subasic

TRITA ITM-EX 2020:38

(4)
(5)

Abstract

Board games are on the rise and chess is no exception. How- ever, in an increasingly digitalized world these board games lack something in comparison to digitalized games, being able to play with anyone anywhere. This project aimed to combine these two worlds by being a physical game of chess where one could play against an opponent from far away.

CheckMate is a robot consisting of an acrylic frame and various electronic components, such as an electromagnet, two stepper motors, a Hall effect sensor and a WiFi mod- ule. The electromagnet and Hall effect sensor were able to move using a belt and pulley system. This allowed mag- netic pieces to be identified and dragged across the board.

The board then communicated the location of all the pieces on the board, using Wifi, to an website that also kept track on whose turn it was.

The result of this project was a robot that was able to perform all the moves necessary on the chessboard as well as communicating to the website. When moving a piece from one location to another the piece repelled other pieces on its way. However, this was deemed to be acceptable since the pieces were not moved too large of a distance for the electromagnet to attract them when moved into its square. One move that the robot was not able to perform was castling. The results can therefore bee seen as a start- ing point toward further developments.

Keywords: Mechatronics, Chess, Arduino, WiFi-module,

Webserver, Hall-effect sensor, Electromagnet

(6)

Referat

Trådlöst Arduino drivet schack

Brädspels popularitet stiger och schack är inget undantag.

Dock saknar brädspel de digitala spelens möjlighet att spela med vem som helst varsomhelst. Detta projekt ville bygga över klyftorna mellan dessa två världar genom att vara ett fysiskt schackspel med de digitala spelens möjligheter.

CheckMate är en robot byggd av akrylplast och diverse elektroniska komponenter sådan som en elektromagnet, två stegmotorer, en halleffektsensor och en WiFi-modul. Elektro- magneten och halleffektsensorn förflyttades via ett system av kuggremmar drivet av stegmotorerna. Elektromagneten användes för att flytta pjäserna på brädet medan halleffekt- sensorn användes vid kartläggning av pjäsernas position på brädet. Brädet kommunicerade, via trådlöst nätverk, till en hemsida som användes för att spara och överföra pjäsernas positioner.

Projektet resulterade i en robot som kunde göra alla mot- svarande drag hämtat från hemsidan. Dock så repellerade en flyttande pjäs på de stationära pjäserna när den passera- de. Detta ansågs dock vara acceptabelt då elektromagneten kunde föra tillbaka pjäserna när den befann sig i dess ruta.

Något som projektet ej lyckades utföra var draget rockad.

Resultatet av detta projekt kan ses som en startpunkt i en vidareutveckling eller en färdig produkt vid obesvärad spelning.

Nyckelord: Mekatronik, Schack, Arduino, Wifi-modul, Webb-

server, Halleffektsensor, Elektromagnet

(7)

Acknowledgements

In the duration of this project we have received loads of help from people whom without their help this project would not have been possible.

We would like to thank Nihad Subasic for providing us with feedback through- out this project and the support given to us during these strange COVID-19 times, Staffan Qvarnström and Thomas Östberg for helping provide and giving guidance with the components for the construction. We would like to thank Seshagopalan Thorapalli Muralidharan for all the help given to us. Finally we would like to thank all of our course mates for the feedback and discussion.

Joakim Ericson & Adam Westermark

Stockholm, May 2020

(8)

Contents

1 Introduction 1

1.1 Background . . . . 1

1.2 Purpose . . . . 1

1.3 Goals and scope . . . . 2

2 Theory 3 2.1 Microcontroller unit . . . . 3

2.2 Internet . . . . 3

2.2.1 Wifi module . . . . 3

2.3 Magnetic sensors . . . . 4

2.3.1 Hall effect sensors . . . . 4

2.3.2 Reed switches . . . . 5

2.3.3 Comparison . . . . 5

2.4 Motors . . . . 6

2.4.1 Stepper motor . . . . 6

2.5 Stepper motor driver . . . . 7

2.5.1 H-Bridge . . . . 7

2.6 Electromagnets . . . . 7

3 Implementation 9 3.1 Construction . . . . 9

3.1.1 Frame . . . . 9

3.1.2 Pulley system . . . 10

3.1.3 Pieces . . . 10

3.2 Electronics . . . 11

3.2.1 Hall effect sensor . . . 12

3.2.2 Push button . . . 13

3.3 Arduino code . . . 13

3.3.1 Movement . . . 14

3.3.2 Mapping pieces . . . 15

3.4 Webserver . . . 15

4 Result 17

(9)

4.1 Physical model . . . 17

4.2 Testing the physical implementation . . . 17

4.2.1 Magnet proximity . . . 18

4.2.2 Magnet strength . . . 18

4.2.3 Electromagnet attracting a piece . . . 19

4.2.4 Positioning . . . 19

4.3 Performance . . . 19

4.4 Communication . . . 20

5 Discussion and conclussions 23 5.1 Discussion . . . 23

5.2 Conclussions . . . 25

6 Recommendations for future work 27 6.1 Recommendations . . . 27

6.2 Future work . . . 27

Bibliography 29 Appendices 31 A Website 33 B Arduino code 35 C Website code 49 C.1 index.html . . . 49

C.2 send.html . . . 50

C.3 update.php . . . 50

C.4 showboard.php . . . 52

C.5 reset.php . . . 53

C.6 ardCheck.php . . . 54

D Components 57

D.1 Product sheet . . . 57

(10)

List of Figures

2.1 Hall effect in a conductive sheet . . . . 4

2.2 Orientation of magnets and sesnors . . . . 5

2.3 A depiction of the wiring in uni- and bipolar stepper motors . . . . 6

3.1 Assembly of the construction . . . 10

3.2 Connection diagram between the electronic components . . . 12

3.3 A flowchart depicting the Arduino code . . . 13

3.4 Schematic chess board, and directions used in the code . . . 14

3.5 The structure of the datatable pos . . . 16

3.6 The structure of the datatable last move . . . 16

4.1 The two types of magnets used, inserted into the pieces . . . 18

4.2 The webpage showboardstate.php showing the board state to a web

browser . . . 20

(11)

List of Tables

4.1 The result of the magnet proximity test . . . 18

4.2 The result of the electromagnet test . . . 19

(12)

List of Abbreviations

CAD Computer Aided Design

DC Direct current

HES Hall effect sensor

HTML HyperText Markup Language ICSP In-circuit serial programming

IP Internet Protocol

PC Personal computer

PHP PHP: Hypertext Preprocessor

PWM Pulse width modulation

USB Universal Serial Bus

(13)

Chapter 1

Introduction

This chapter introduces the background, purpose, goals and scope of the project.

It aims to provide the context in which this project was constructed as well as the projects intentions and limitations.

1.1 Background

In an increasingly digitalized world some people still value playing games with physical pieces on a physical board. According to a 2019 study [1] the global playing cards and board games are on the rise. The ancient game of chess - the roots of the game can be traced as far back as before the 6th century [2] - is no exception.

Even with the rise of incorporated technologies in chess the longing for the analog game is still there. These physical games does however lack some conveniences of their digital brethren, such as being able to play with anyone, anywhere. There has been previous attempts at creating physical board games of chess with convenience of digitalized games where players can play together from different locations [3–5].

However, these project have used a large amount of sensors, which drives up the cost.

1.2 Purpose

The purpose of this project was to combine the feeling of playing a physical board game with the convenience of digitalized games where players can play together from different locations. To make the boards convenient for home use it was decided that the boards should not use any crane to move the pieces and instead the movement should stem from under the board. The project aspired to answer the following research questions:

• How can the boards be connected to each other?

• How can the board register and keep track of the different pieces using only

one sensor?

(14)

CHAPTER 1. INTRODUCTION

1.3 Goals and scope

The ultimate goal of this project was to create two physical boards of chess that could record and send moves between each other, as well as being able to execute moves being made on the opposite board. Due to time constraint of five months part time work, this was done in the following steps:

• Create a board that can move a piece in both x- and y- direction

• Implement registration and mapping of the pieces

• Connect the board to the internet and use the internet to make moves on the board

• If possible, make another board and connect the two The project also aimed to keep the cost as low as possible.

2

(15)

Chapter 2

Theory

This chapter provides the fundamental theoretical background of this project and its components.

2.1 Microcontroller unit

A microcontroller is a small circuit board that can be programmed to control a great number of things, such as sensors and motors. The Arduino Uno is one of the most popular microcontrollers on the market, much due to how easy it is to program and the simple design of it. It can interpret both analog and digital signals, it also has an Universal Serial Bus (USB) connection and a reset button.[6]

2.2 Internet

Communication between devices at great distance from each other can be easily achieved using the internet. Devices on the internet communicate using web servers.

These servers store data which can be provided to other devices (called clients) when requested. To locate servers and clients on the web, Internet Protocol (IP) addresses are used. An IP address specifies the location of a specific device on the internet [7].

2.2.1 Wifi module

Connecting an Arduino to the internet can be done through connecting a WiFi

module to the Arduino. A cheap option is the ESP8266. The module allows con-

nection to the internet by sending and receiving radiowaves with information that

can be caught by nearby internet routers [8]. Through the wifi module a server can

be setup which allows the Arduino to connect to a computer or another Arduino

[9]. An alternative to this is to set up a server with a separate computer, this would

however mean that the dedicated computer would have to be on for the chessboard

to work [10].

(16)

CHAPTER 2. THEORY

2.3 Magnetic sensors

An easy way to detect where the chess pieces are on the board is to integrate magnets into their design, which can be sensed by magnetic sensors under the board. Previous projects have used this to great effect [3, 4]. Those projects used reed switches as the sensors, however, Hall effect sensors (HES) are also an option [5, 11].

2.3.1 Hall effect sensors

HES are sensors that are built around Hall elements. These elements are activated by an external magnetic field and produces an output signal that grows in strength as a function of the magnetic-field around the sensor. How this signal gets treated by the HES depends on its type. There are two types HES, digital and analog.

Analog versions takes the signal and amplifies it to a output voltage. This means that the output voltage of the sensor, often called Hall voltage V

H

, is proportional to the strength of the magnetic field. Digital versions of the sensors on the other hand, only has an ”ON” and an ”OFF” state. The sensor enters the ”ON” state whenever the magnetic flux around it is big enough. This means that the sensor cant distinguish between two magnetic fields with different flux, as long as the flux of both fields exceeds the threshold.[12]

The Hall effect is illustrated in Figure 2.1.

(a) (b)

Figure 2.1: Hall effect in a conductive sheet [13]

In Figure 2.1a a current is running through a sheet of conductive material, often semi-conductive, with a pair of probes on opposite sides connected to a voltmeter,

4

(17)

2.3. MAGNETIC SENSORS

measuring the voltage to zero. In Figure 2.1b a magnetic field is applied to the plate at an orthogonal angle and the voltmeter measures the Hall voltage.[13]

Moving a magnet and a sensor in a sideway motion relative each other, with a fixed distance, is called sideway detection. Sideway detection is useful for detecting the presence of a magnetic field.[12]

2.3.2 Reed switches

Reed switches consists of two magnetic contacts enveloped by glass. When sub- jected to a magnetic field, these contact draws closer to each other and completes a circuit.[14]

2.3.3 Comparison

A big difference between Reed switches and HES are that certain HES can give an analog signal while Reed switches only gives digital signals. The orientation of the magnets to be detected also differs. The axis of the magnet should be parallel to Reed switches but perpendicular to HES [15], see Figure 2.2.

Figure 2.2: Orientation of magnets and sensors [15]

Since analog HES are able to register different level of magnetic flux, they could be

used in the project to register either black or white pieces by having magnets with

different magnetic flux in them.

(18)

CHAPTER 2. THEORY

2.4 Motors

A simple direct current (DC) motor works by using a looped wire connected to a rotor in a magnetic field. The wire is given current by a commutator which means that the magnitude of the magnetic torque, ·, equals to

· = IBA| sin(„)|. (2.1)

In (2.1) I is the current provided to the motor, B is the strength of the magnetic field inside the motor, A is the area of the loop and „ is the angle between the magnetic field and the loop plane. The torque acts on the wire and causes it to spin. To increase the torque and to avoid making it uneven, DC motors often uses multiple wires turned into coils. The coils increase the torque and by having multiple of them set at different angles, the torque can remain relatively constant.[16]

2.4.1 Stepper motor

One type of DC motor is the stepper motor. These are able to be accurately controlled by turning in discrete steps. It does this by organizing the coils in phases and energizing them in a sequence. They are most efficient at low speeds. Stepper can be either bipolar or unipolar. The difference is that unipolar stepper motors has one lead that always is negative and one that is positive. Because of this only half the coils can be used at a time. Bipolar steppers on the other hand can have alternating current through the phases which means that the polarity can be switched and allows all the coils working at the same time. The implications of this is that bipolar steppers generally have better efficiency and produces a higher torque, however it also needs a more complicated control system with H-bridges since they need alternating current.[17] Figure 2.3 illustrates the wiring in uni- and bipolar stepper motors.

Figure 2.3: A depiction of the wiring in uni- and bipolar stepper motors [17]

6

(19)

2.5. STEPPER MOTOR DRIVER

2.5 Stepper motor driver

The purpose of a stepper motor driver is to convert step commands coming from the machine controller to correct on-off patterns required to drive the stepper mo- tor. Therefore the driver’s two primary functions are to sequencing the phases and controlling the phase current.[18]

The type of driver used needs to be compatible to the stepper motor. A unipo- lar motor needs a unipolar driver and bipolar motors requires bipolar drivers. The alternating current in the phases in a bipolar motor means that the driver needs to have two H-bridges to allow for this.[17]

2.5.1 H-Bridge

In order to control the rotating direction of a DC motor one can simply reverse the direction of the current flow through the motor. An H-bridge allows DC motors to run both backward and forward by activating two, of four, particular switches at the time, thus changing the rotation direction of the motor.[19]

2.6 Electromagnets

An electromagnet is a device consisting of a core of magnetic material surrounded

by a coil through which an electric current is passed to magnetize the core. Elec-

tromagnets are used when controllable magnets are required, for example when the

magnetic flux is to be varied or be turned on respectively off.[20]

(20)
(21)

Chapter 3

Implementation

The implementation of the physical construction and digital code was done simul- taneously. A Computer Aided Design (CAD) model was created to test different design solutions while first drafts of the code was written. When the CAD model was finished, the acrylic frame was cut and the custom pieces 3D-printed.

3.1 Construction

The first thing to be decided was the size of the chess pieces and the squares of the chessboard. Based on the size of the cheap magnets available, the pieces was given the dimension to 18 mm in diameter and the squares the size 4◊4 cm. Based on this, the maximum size of the available laser cutter and the philosophy that for home use smaller was better, a model was created in the CAD program Solid Edge. Metal rods were implemented in the design in order to support the xy-coordinate system under the board. The final dimensions of the chessboard became 55◊48◊12, 8 cm.

When all the parts had been assembled, the physical construction could begin.

The parts were mounted according to the Solid Edge model.

3.1.1 Frame

The frame was made out of 3 mm thick acrylic which was laser-cut and engraved

in the style of a traditional chessboard. Two holes were cut out of each long side

in order to fit the supporting metal rods. Underneath the board the components

necessary for the movement of the pieces was placed. Figure 3.1 shows an assembly

of the construction.

(22)

CHAPTER 3. IMPLEMENTATION

Figure 3.1: Assembly of the construction, made in Solid Edge 2019

3.1.2 Pulley system

One of the primary challenges of the construction, moving the electromagnet and subsequently the pieces, was solved using a pulley system. The system transfers the torque generated by the stepper motors to belts which gets pulled back and forth.

Two belts connected by PVC pipes are static and stands at the bottom of the frame while a third belt moves with the rotation of the first two. The electromagnet is connected to the rotation of the third belt. In other words, belt one and two controls the x-axis of the electromagnet while belt three controls its y-axis. The whole system is supported by metal rods which stabilizes everything.

3.1.3 Pieces

Magnets were integrated into the design of the pieces in order for magnetic sensors below the board to detect the pieces. This was done by 3D printing hollow pieces to allow for the magnets to be put inside.

When choosing what magnets to use for the chess pieces, three factors were con- sidered. Their size, cost and relative strength. The relative strength between the

10

(23)

3.2. ELECTRONICS

magnets to be incorporated in the white and black pieces was important in order for the HES to give different signals depending on the color of the piece. The chosen magnets were N35 Neodymium and Y28 Ferrite magnets. The product sheets for both magnets can be found in Appendix D. Generally, magnets made of Neodymium is much more magnetic then ones made from Ferrite. [21]

3.2 Electronics

The electrical components used were the following:

• One Arduino uno

• Two breadboards

• Two bipolar stepper motors

• Two stepper motor drivers

• One wifi-module, ESP8266

• One analog Hall effect sensor

• One electromagnet

• One capacitor 470 µF

• One push button

• One resistor 10 k

• One resistor 1 k

• One power supply 9 V

• One circuit board

The components were connected accordingly to Figure 3.2.

(24)

CHAPTER 3. IMPLEMENTATION

Figure 3.2: Connection diagram between the electronic components, made in Fritz- ing and paint.net

3.2.1 Hall effect sensor

As previously mentioned, in section 1.1 Background, there have been similar projects to this before. However, some of them used HES under each square of the board. To meet this projects goal on making a cheaper option and expanding on other projects it was decided to only use one HES. The HES was placed with the electromagnet, and the two, more or less, took turns being active, to enable it to move around and thereby knowing where the pieces were located. As presented in section 2.3.1 Hall effect sensors, having an analog HES enabled to differ between white and black pieces by having magnets of different magnetic flux and therefore producing different V

H

.

12

(25)

3.3. ARDUINO CODE

3.2.2 Push button

To ease the playing mechanics a push button was installed. The button was used to send and retrieve information from the server.

3.3 Arduino code

The Arduino code provided the necessary functions, such as moving the pieces, mapping the pieces on the board, and allowing for communication to the server, needed to operate two communicating boards. The code follows the logic presented in Figure 3.3.

Figure 3.3: A flowchart depicting the Arduino code, drawn using draw.io

(26)

CHAPTER 3. IMPLEMENTATION

The code itself can be found in Appendix B.

In the code, the board was seen as by Figure 3.4, with the edge of the playing area in blue and edge of the construction in red.

y

x (0, 0)

(7, 7) Up

Left Down Right

Figure 3.4: Schematic chess board, and directions used in the code, drawn in TeXShop using tikzpicture

Setting the outer edges of the board helped control the positioning by setting a limit on how far the movement could be made, when for example scanning the board.

3.3.1 Movement

The movement of the pieces on the board was achieved using a electromagnet un- der the board, which was moved using the pulley system. When a piece was to be moved, the electromagnet was positioned under the specified piece, activated and moved to the right position. In order to ease the positioning, the function to move a square in each position was programmed and used throughout the code. Moving half a square in each direction was also programmed and used when removing pieces from the board as well as moving pieces from one square to another.

A piece that moves on the board would have to be moved between squares, on the edges, in order to avoid contact with other pieces. This was implemented by first moving a half square in x-direction, then moving half a square too far in y-direction, thereafter moving to the correct x-location and finally to the correct y-location.

If the opponent captured a piece on their turn, the captured piece would first have to be removed from the board before the opponents piece could be moved into its square. The board was designed with extra space in x-direction to allow for re- moved pieces to be stored there. The code was written so that the to-be-removed piece was, before the removal, read by the HES and depending on it it was a black or white piece it was stored on different sides. The removal was done by moving a half square towards the middle of the board, to avoid contact with other pieces on the way out, and thereafter moved a square beyond the playing area in x-direction.

14

(27)

3.4. WEBSERVER

It was necessary to move a half square towards the middle of the board since there was no extra space in y-direction beyond the edges of the board, and if the to-be- removed pieces was for example located at (3, 0) or (6, 7) it would not be possible to move a half square towards the edge.

3.3.2 Mapping pieces

For one board to make the move that has been played on the other the board, the boards need to know what piece has been moved and to what location. This was done by saving values, depending on the V

H

(given by the HES) for each square, into a two dimensional array. Depending on the V

H

one of three different values cor- responding to either white piece, black piece or empty square was stored in the array.

As Figure 3.3 shows there was both a need to save a piece‘s new location and a need to scan the board and to send that array to the other board. To save a piece new location was done in the code by copying the opponents array as your own, after making the corresponding moves.

Since only one HES was used, the board had to be scanned in order for the board to know what move has been made. The scanning of the board worked by first returning the HES to the starting position (7, 0) and thereafter moving it row by row, both left and right, to the end position (7, 7), as seen in Figure 3.4. For each square it passes, it reads and stores the value corresponding to the V

H

into the coinciding element in the two dimensional array.

3.4 Webserver

In order for different devices to communicate through the internet, a server was needed. It was set up on a personal computer (PC) running the operating system Windows 10 using the Web development platform WampServer, which can create websites with HyperText Markup Language (HTML), PHP: Hypertext Preproces- sor (PHP) and the database platform MariaDB. The process of setting up the server included opening a network port, an address for a specific process, on a local inter- net router. When the server was set up any web browser connected to the internet could easily access the sever, provided the correct IP address and port number.

The website was given was given capability to handle requests from both Arduinos

and web browsers using a GET method. To achieve this, the Arduino was pro-

grammed to access a web page different from the default one. All the code files in

Appendix C was placed in the the www directory created by WampServer. The

datatable of the database structures can be seen in Figures 3.5 and 3.6.

(28)

CHAPTER 3. IMPLEMENTATION

Figure 3.5: The structure of the datatable pos

Figure 3.6: The structure of the datatable last move

16

(29)

Chapter 4

Result

This chapter presents the result of the project and its performance. Only one board was able to be constructed.

4.1 Physical model

The physical model was constructed in accordance to section 3.1 Construction.

However, due to poor tolerance in the 3D printing of the customary parts, some of the holes had to be drilled afterwards in order to save time. This was done with a power drill, which resulted in some of the holes being angled.

The goal of the design of the construction was to allow for the full range of necessary movement while still being as small as possible. This was achieved by allowing the electromagnet and HES to move as much as necessary in both x-and y-direction and subsequently the board itself was only supported by its side frame. This combined with the flexible nature of the acrylic made the board sag, and consequently the distance between the electromagnet and the piece differed depending on the location on the board

In order to save time, 16 identical cylinder pieces, in both colors, were 3D-printed.

This still allowed for the board to distinguish black- and white pieces. However, for the player this created a problem since a number of turns into a game it could be problematic to remember what cylinder represented what piece. This could easily be solved by writing the first letter of the respectively piece on top of it, for the king a crown symbol could be used.

4.2 Testing the physical implementation

It was crucial to the performance that the code could be followed through without

the physical implementation preventing this. Hence, a few tests were constructed.

(30)

CHAPTER 4. RESULT It was necessary to test how close to each other two magnets could be without repelling each other. In order to know how accurate the positioning in x-and y- direction needed to be, it was necessary to test how far from a piece the electro- magnet and HES could be and still function as planned. Thereafter a test to see how accurate the positioning itself was carried out.

4.2.1 Magnet proximity

Two pieces were placed on a fix distance from each other‘s center. One piece was slowly pushed toward the other until the stationary piece moved. Then the distance from the center of the pushed piece to the original positioning of the stationary piece’s center was measured. The test was performed ten times and the arithmetic mean of the results is shown in Table 4.1.

Table 4.1: The result of the magnet proximity test in [cm]

Pushed piece / stationary piece White Black

White 2,8 2,7

Black 2,6 2,2

4.2.2 Magnet strength

The signals from two different HES, one with the sensitivity 2,5 mV/G and the other with 5,0 mV/G was tested in position directly under the magnets on the board, approximately 5 mm below. None of the sensors could differentiate between the N35 and Y28 magnets with a margin greater than 5%. This is likely because the N35 magnets were much smaller than the Y28 magnets see Figure 4.1.

Figure 4.1: The two types of magnets used, inserted into the pieces

18

(31)

4.3. PERFORMANCE

4.2.3 Electromagnet attracting a piece

To see how close to the center of a piece the electromagnet needed to be in order to be able to attract and move a piece the following test was executed.

The electromagnet was placed in a fix position underneath the acrylic top sheet.

Thereafter a piece was placed on a fix distance away from the center of the elec- tromagnet and the electromagnet was activated with a push button. If the electro- magnet attracted the piece the distance between the two centers was increased and the test followed through again. The test was performed on two separate locations, in the middle on the board and on the bottom right corner of the board, since the distance between the electromagnet and the piece was at largest on the bottom right corner and closest in the middle. The test was performed ten times on each location and the arithmetic mean of the test is presented Table 4.2.

Table 4.2: The result of the electromagnet test in [cm]

White Black In the corner 1,7 1,7 In the middle 1,8 1,7

4.2.4 Positioning

An essential part of this project was that the positioning was working as intended and without any large errors. The previous test in section 4.2.3 provided results in how close to the center of a piece the position of the electromagnet needed to be. These restrictions resulted in that the margin of error when positioning the electromagnet was: 1,7 cm. To ensure that a cultivated error when moving multiple squares did not occur the margin of error was set to

1,78

cm when moving one square.

To test that the movement did not exceed this margin of error the following test was implemented. The centers of two squares, n squares apart, were marked. The starting position of the board was set to one of the squares before it was moved n squares away toward the other center. This test was conducted for a number of different n values in different directions. The end position was always within 1,7 cm from the center the square and therefore the movement of the position was seen as acceptable.

4.3 Performance

Overall the performance of this model was deemed to be acceptable.

The result presented in Table 4.1 with the magnet proximity test showed that a

piece might affect other pieces when moved. Since moving a piece along the edge of

(32)

CHAPTER 4. RESULT a square only provides 2 cm distance to that square‘s center it ensures that a piece that might be located in that square is affected by the moving piece and moved.

This however, was not an issue since a comparison with the result rendered in Table 4.2 entails that the piece is able to move back to its center with the activation of the electromagnet.

The decision to only use one HES induced the need to scan the board. This in turn resulted in a slower possible game, since the players needed to wait for the scanning process. The total scanning times was two minutes and 20 seconds.

When moving a half square in any direction, the piece lingered and was not moved as much as the electromagnet. Different speeds were tested for moving a half square and did not provide any notable different outcome.

Two moves that were not able to be made were en passant and castling. This was because the Arduino code only allowed for a difference in two squares for each move.

4.4 Communication

The board was not able to connect with the standard 5,0 and 2,4 MHz WiFi signal from a local router. It could however connect with the internet hotspot provided by an Android phone. It could with a 100% replication rate both send and receive data to/from the website. Figure 4.2 shows how the positioning of the pieces could be viewed from the website.

Figure 4.2: The webpage showboardstate.php showing the board state to a web browser

20

(33)

4.4. COMMUNICATION

More pictures of the website can be found in Appendix A.

(34)
(35)

Chapter 5

Discussion and conclussions

5.1 Discussion

During this project KTH made the decision to shutdown its campus due to COVID- 19. This affected this project by not having access the usual equipment one might expect. Therefore many solutions to eventual problems in the construction of this project had to be improvised and might have affected the end result.

One of the biggest challenges of this project was making the belt and pulley system run smoothly. The system had to be rebuilt several times in order for them to work consistently. The PVC pipes between the two belts that run in the x-direction was added after the first version couldn’t move at all. Another thing that helped the system was to polish the metal rods with very fine sandpaper. The tools available when working from home was not optimal and might have resulted in some of the parts being angled and having a rough surface. This might have resulted in in the construction not being as accurate and stable as intended. Combining this with the fact that the assembly of the construction needed to be very exact in order to ensure that the parts lined up perfectly resulted in the pulley system being very sensitive.

As previous said in section 4.2, when moving a piece along the edge of a square, pieces in the adjacent squares was affected by the moving piece and repelled. Since a square was 4 ◊ 4 cm and therefore the distance of the edge to the middle of a square 2 cm the stationary piece moved at most 0.8 cm based on Table 4.1. Con- sidering Table 4.2, the electromagnet could easily within that distance attract that piece back into its square‘s center, and hence, this was not seen as a problem.

As given by Table 4.1 magnets were affected if they were located in a square a

moving magnet was passing by. This in turn meant that the HES might give a

different V

H

for a piece not located in the center of a square compared to if it was

in the center. Ergo the HES might misread the white for a black piece, and might

(36)

CHAPTER 5. DISCUSSION AND CONCLUSSIONS not register a black piece at all. This was partially solved in the Arduino code by activating the electromagnet to attract the piece and thereafter deactivating the electromagnet before reading the HES. This ensured that the piece was in a position almost straight above the HES before it was read. This reduced the error of the HES, but since the margins in the signal value were so small, see section 4.2.2, the results were still inconsistent.

One decision that was taken pursuing the goal of reducing the cost was only using one HES. This, as said in section 4.2 resulted in a slower game since the board needed to be scanned. This however, was not seen as an obstacle. The goal of this project was not to create the fastest possible long distance physical chess game.

Instead it aimed to explore different options when constructing a long distance physical chess game. If one wished to play with competitively rules - such as the so called touch move rule, 4.3 in [22], or with a chess clock, article 6 in [22] - this project would not anyway be able to meet those requirements and hence the need for speed was obsolete. It is also possible for a chess game to last a very long time [23], and since this project was intended for home use where players could engage in other activities between moves, it might not matter that much that the scanning of the board takes some time. The implementation of the push button also makes it easier to go long time between moves since the opponents move on ones board only is made after the press of the button. This entails that the player is ready and allow the player to see the opponent‘s move being made.

The fact that a piece lingered when moving half a square in one direction, was not seen as a large defect. When moving in any direction it is more favorable for the positioning of the electromagnet and HES to be correct rather than a piece.

This is because the piece can with the activation of the electromagnet be brought back into the right position.

As mentioned in section 3.1.3 identical pieces, in both colors, were 3D-printed.

The original plan to create specific pieces to each position was however, closely followed. This was since the original plan for the pieces was to create them in two steps, first the identical cylinders and subsequently create an upper part to allow for distinction. The result was nonetheless considered good enough since it served the same purpose as the original intended pieces in all ways but esthetic.

One way to reduce the cost was the decision to use only one HES. Another ap- proach to this was to 3D print all the components, instead of buying them. In addition to this the chess board itself was made of acrylic and laser cut and en- graved in order to reduce the cost.

When installing the ESP8266 the source provided by the distributor urged to only give the module 3,3 volt [24], however, this proved not to work and it had to be given 5 V to work.

24

(37)

5.2. CONCLUSSIONS

The created website used, as mentioned in section 3.4, GET request to relay data.

This is however not the most safe way to transfer data as it does not provide any encryption. However, since the transferred data only consists of chess moves and not private information, this was not seen as a large issue.

5.2 Conclussions

In conclusion, the result and answer to the research questions were the following.

How can the boards be connected to each other?

Connecting two separate boards could be done via a webserver that is able to handle data using the internet. There were originally some struggle setting up the WiFi module ESP8266 but after that it worked fine.

How can the board register and keep track of the different pieces using only one sensor?

In order to make due with using only one sensor, it has to be able to move around as well as differentiate between black and white pieces. Installing an anaolog HES on the same module as the electromagnet is a great way to move the sensor. This also allows the electromagnet to centralize the pieces above the HES and subsequently providing a more accurate output. By using an analog HES the black and white pieces could be differentiated by having magnets of different magnetic flux inside the pieces. The implementation of only one HES resulted in the need to scan the board in order to know what move the player made during their turn. Consequently the potential time between moves was increased.

Using an online database to store the positions of every piece worked great. The

response time was quick and everything was easily accessible.

(38)
(39)

Chapter 6

Recommendations for future work

This chapter aims to provide recommendations for improvements for the existing project as well as suggestions for future work.

6.1 Recommendations

When assembling the construction it was of the utter most necessity to be precise to avoid misalignment. If not the transmission of the belt will become irregular.

The pulley system was also one part of this project that required much time. To make this part of the project easier, it might be beneficial to use bearings.

6.2 Future work

As mentioned in section 4.2 the magnets, when passing, affected each other. Future revisions of this project should aim to fix this problem. One way this could be done is by using magnets with a lesser field strength compared to the ones used in this project. The magnets might not then affect each other and remain in the center of the square. Another solution is to simply make the board larger.

Another way to improve upon this project would be to use magnets of more vary- ing strengths, since the HES could not always distinguish between black and white pieces. In future work it is also worth investigating the optimal strength of the magnets.

Another improvement that could be made is to allow for castling and en passant.

In addition the security of the website could be upgraded, for example using POST

method instead of GET.

(40)
(41)

Bibliography

[1] (2018, Sep) Visited: 2020-01-31. [On-

line]. Available: https://www.grandviewresearch.com/

industry-analysis/playing-cards-board-games-market?fbclid=

IwAR19aUx92YuV2iouMPUdmou5oR4dDEBjYYcy9D6-NnICX8W8RLnfvwjZ6IA [2] A. E. Soltis. (2019, Dec) Chess. Visited: 2020-01-31. [Online]. Available:

https://www.britannica.com/topic/chess/Development-of-theory

[3] M. A. Chhangani, “Arduino based wireless powered chess,” International Jour- nal of Innovative Research in Computer and Communication Engineering, vol. 3, no. 4, 2015, doi: 10.15680/ijircce.2015.0304139.

[4] R. Seyed Farshchi, “The chess robot,” Bachelor’s Thesis, KTH, 2015, diva id: diva2:916283. [Online]. Available: http://kth.diva-portal.org/smash/get/

diva2:916283/FULLTEXT01.pdf

[5] D. Bhutani, Y. Ali, and P. Gupta, “Design and implementation of a wire- less remote chess playing physical platform,” International Journal of Engi- neering Research and Technology, vol. V6, no. 09, Sep 2017, doi: 10.17577/

IJERTV6IS090020.

[6] What is an arduino? Visited: 2020-05-11. [Online]. Available: https:

//learn.sparkfun.com/tutorials/what-is-an-arduino

[7] D. Gourley, B. Totty, M. Sayer, S. Reddy, and A. Aggarwal, HTTP: The Defi- nite Guide, 1st ed., L. Mui, Ed. 1005 Gravenstein Highway North, Sebastopol, 1005 Gravenstein Highway North, Sebastopol, CA 95472.: O’Reilly Media, Inc., Sep 2002.

[8] H. Johansson, Elektroteknik. KTH ITM, 2013.

[9] Wifi library. Visited: 2020-02-16. [Online]. Available: https:

//www.arduino.cc/en/Reference/WiFi?fbclid=IwAR3fa7DrBv5OITts7kVQw o1-iuiMyXj0VoBIHH0I9tLngZQHXOpaTip4eM

[10] (2016, 10) What is a web server? and which web server software is there?

Visited: 2020-02-16. [Online]. Available: https://www.ionos.com/digitalguide/

(42)

BIBLIOGRAPHY server/know-how/web-server-definition-background-software-tips/?fbclid=

IwAR0OGUNGL3jbvsIB1dR3FAZOJDZRqbU5rRhf24kTg37Sd6VWIPjTsNyQnpE [11] F. Suˇsac, I. Aleksi, and Z. Hocenski, “Digital chess board based on array

of hall-effect sensors,” in 2017 40th International Convention on Information and Communication Technology, Electronics and Microelectronics (MIPRO).

IEEE, 2017, pp. 1011–1014, doi: 10.23919/MIPRO.2017.7973572.

[12] (2018, Feb) Hall effect sensor. Visited: 2020-02-07. [Online]. Available: https:

//www.electronics-tutorials.ws/electromagnetism/hall-effect.html?fbclid=

IwAR2q8ZlindSqy-fSlfHdLI93j2fyWat8gqLqgn2UBb19uOe-uM-jYSa8-Ho [13] E. Ramsden, Hall-Effect Sensors: Theory and Application, 2nd ed. Elsevier

Inc, 2006.

[14] Z. Talib, “Investigation of fast high voltage pdc measurement based on a vacuum reed-switch,” Master’s thesis, KTH, EES, 01 2011, diva id:

diva2:511557. [Online]. Available: https://www.diva-portal.org/smash/get/

diva2:511557/FULLTEXT01.pdf

[15] I. K & J Magnetics. Reed switches and hall effect sen- sors. [Online]. Available: https://www.kjmagnetics.com/blog.asp?p=

reed-switches-and-hall-effect-sensors

[16] H. D. Young and R. A. Freedman, Univerisity Physics with Modern Physics, 14th ed. Pearson Education Limited, 2016.

[17] B. Earl. (2019, 01) All about stepper motors. Visited: 2020- 05-29. [Online]. Available: https://cdn-learn.adafruit.com/downloads/pdf/

all-about-stepper-motors.pdf?timestamp=1590748807

[18] B. Porter. (2019, Apr) What’s a stepper motor driver and why do i need it? Visited: 2020-12-02. [Online]. Available: https:

//all3dp.com/2/what-s-a-stepper-motor-driver-why-do-i-need-it/

[19] Arduino dc motor control tutorial - l298n — pwm — h-bridge. Visited:

2020-02-12. [Online]. Available: https://howtomechatronics.com/tutorials/

arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/

[20] (2014, Jan) Visited: 2020-02-07. [Online]. Available: https://www.britannica.

com/science/electromagnet

[21] Permanent magnet standard items. Visited: 2020-05-11. [Online]. Available:

https://www.magfine.co.jp/eng/magnet/comparison.html

[22] I. C. Federation. Fide laws of chess. Visited: 2020-05-29. [Online]. Available:

https://www.fide.com/FIDE/handbook/LawsOfChess.pdf

30

(43)

BIBLIOGRAPHY

[23] G. W. Records. Most moves in a chess game. Visited: 2020-05-11.

[Online]. Available: https://www.guinnessworldrecords.com/world-records/

68297-most-moves-in-a-chess-game

[24] (2016, 06) Esp8266 serial wifi module. Visited: 2020-

05-29. [Online]. Available: https://www.itead.cc/wiki/ESP8266

Serial WIFI Module?fbclid=IwAR0w4eZ4m5XvYFvXdeKIXw5Bbozcffl

LNKRevpFGUFwj1j0xDc97T4HX3Y

(44)
(45)

Appendix A

Website

Various pictures from the different web pages.

(46)

APPENDIX A. WEBSITE

34

(47)

Appendix B

Arduino code

This code was loaded to the Arduino.

// Project name : CheckMate

// // Date : 29/05≠2020

// D e s crip tio n : Bachelor t h e s i s in Mechatronics at KTH ITM.

// Turns the Arduino i n t o a chess robot that can

// send and r e c e i v e moves from a website . // Written by : Joakim Ericson & Adam Westermark

// Examinator : Nihad Subasic // TRITA≠nr : 2020:38

// Course code : MF133X

// L i b r a r i e s

// Used by m i c r o c o n t r o l l e r s for communication

#i n c l u d e <SPI . h>

// Used by the esp8266 for communication with the i n t e r n e t

#i n c l u d e <S o f t w a r e S e r i a l . h>

// Motors

// Pins for motors

#d e f i n e dirPinY 2

#d e f i n e stepPinY 3

#d e f i n e dirPinX 4

#d e f i n e stepPinX 5 //Used for movement

#d e f i n e stepsPerRevolution 200

(48)

APPENDIX B. ARDUINO CODE // Electromagnet

#d e f i n e electromagnetPin 7 // Hall≠e f f e c t sensor

#d e f i n e hallSensorPin A0 f l o a t hallValue ;

// Button

#d e f i n e buttonPin 9

i n t buttonState = 0 ; // v a r i a b l e w i l l change // Wifi≠module

#d e f i n e RX 10

#d e f i n e TX 11

// These S t r i n g s depend on what w i f i network

//you are using and what s e r v e r you wish to connect to

String AP = ”your AP” ; // Access point ( the name of the w i f i ) String PASS = ” your Password ” ; // Password ( for the w i f i )

String HOST = ” your Server ” ; // Server name String PORT = ” your ServerPort ” ; // Port name

S o f t w a r e S e r i a l esp8266 (RX,TX) ; / / Makes the esp8266 a S o f t w a r e S e r i a l o b j e c t // Location of the p i e c e s on each board r e s p e c t i v e l y ,

//0≠>empty square , 1≠>white piece , 2≠>black piece //Board 1 i s the p h y s i c a l board ,

// board 2 i s the l a s t board gotten from the website i n t board1 [ 8 ] [ 8 ] = {{2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 } ,

{ 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } } ;

i n t board2 [ 8 ] [ 8 ] = {{2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 } , { 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 } ,

{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ,

{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ,

{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ,

{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ,

{ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } ,

36

(49)

{ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } } ;

// Variables used to keep track of where the board the electromagnet i s //Home p o s i t i o n i s ( 7 , 0 )

f l o a t x=7;

f l o a t y=0;

// Storing

i n t cArray [ 5 ] ; // an array used to compare the two boards

i n t i c ; // used as counters for i t e r a t i n g through the two≠dimensional array i n t j c ;

//Movement , used when moving to a new l o c a t i o n i n t xTarget ;

i n t yTarget ;

void setup ( ) {

pinMode ( stepPinY , OUTPUT) ; pinMode ( dirPinY , OUTPUT) ; pinMode ( stepPinX , OUTPUT) ; pinMode ( dirPinX , OUTPUT) ;

pinMode ( electromagnetPin , OUTPUT) ; pinMode ( hallSensorPin , INPUT ) ; pinMode ( buttonPin , INPUT ) ;

S e r i a l . begin ( 9 6 0 0 ) ; esp8266 . begin ( 9 6 0 0 ) ; }

// Functions to change p o s i t i o n

//k i s the amount of s t e p s to be taken in a d i r e c t i o n void squareUp ( i n t k ){

d i g i t a l W r i t e ( dirPinY , LOW) ;

for ( f l o a t i = 0 ; i < k 0.8 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

d i g i t a l W r i t e ( stepPinY , HIGH) ; delayMicroseconds ( 2 0 0 0 ) ; d i g i t a l W r i t e ( stepPinY , LOW) ; delayMicroseconds ( 2 0 0 0 ) ; } delay ( 1 5 0 0 ) ;

y≠=k ;

}

(50)

APPENDIX B. ARDUINO CODE

void squareDown ( i n t k ){

d i g i t a l W r i t e ( dirPinY , HIGH) ;

for ( f l o a t i = 0 ; i < k 0.8 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

d i g i t a l W r i t e ( stepPinY , HIGH) ; delayMicroseconds ( 2 0 0 0 ) ; d i g i t a l W r i t e ( stepPinY , LOW) ; delayMicroseconds ( 2 0 0 0 ) ; } delay ( 1 5 0 0 ) ;

y+=k ; }

void squareRight ( i n t k ){

d i g i t a l W r i t e ( dirPinX , HIGH) ;

for ( f l o a t i = 0 ; i < k 0.8 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

d i g i t a l W r i t e ( stepPinX , HIGH) ; delayMicroseconds ( 2 0 0 0 ) ; d i g i t a l W r i t e ( stepPinX , LOW) ; delayMicroseconds ( 2 0 0 0 ) ; } delay ( 1 5 0 0 ) ;

x+=k ; }

void squareLeft ( i n t k ){

d i g i t a l W r i t e ( dirPinX , LOW) ;

for ( f l o a t i = 0 ; i < k 0.8 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

d i g i t a l W r i t e ( stepPinX , HIGH) ; delayMicroseconds ( 2 0 0 0 ) ; d i g i t a l W r i t e ( stepPinX , LOW) ; delayMicroseconds ( 2 0 0 0 ) ; } delay ( 1 5 0 0 ) ;

x≠=k ; }

void halfSquareUp (){

d i g i t a l W r i t e ( dirPinY , LOW) ;

for ( f l o a t i = 0 ; i < 0.4 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

38

(51)

d i g i t a l W r i t e ( stepPinY , HIGH) ; delayMicroseconds ( 3 0 0 0 ) ; d i g i t a l W r i t e ( stepPinY , LOW) ; delayMicroseconds ( 3 0 0 0 ) ; } delay ( 1 5 0 0 ) ;

y≠=0.5;

}

void halfSquareDown (){

d i g i t a l W r i t e ( dirPinY , HIGH) ;

for ( f l o a t i = 0 ; i < 0.4 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

d i g i t a l W r i t e ( stepPinY , HIGH) ; delayMicroseconds ( 3 0 0 0 ) ; d i g i t a l W r i t e ( stepPinY , LOW) ; delayMicroseconds ( 3 0 0 0 ) ; } delay ( 1 5 0 0 ) ;

y+=0.5;

}

void halfSquareRight (){

d i g i t a l W r i t e ( dirPinX , HIGH) ;

for ( f l o a t i = 0 ; i < 0.4 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

d i g i t a l W r i t e ( stepPinX , HIGH) ; delayMicroseconds ( 3 0 0 0 ) ; d i g i t a l W r i t e ( stepPinX , LOW) ; delayMicroseconds ( 3 0 0 0 ) ; } delay ( 1 5 0 0 ) ;

x+=0.5;

}

void h a lf S q u a re L e f t (){

d i g i t a l W r i t e ( dirPinX , LOW) ;

for ( f l o a t i = 0 ; i < 0.4 stepsPerRevolution ; i++) { // These four l i n e s r e s u l t in 1 step :

d i g i t a l W r i t e ( stepPinX , HIGH) ;

delayMicroseconds ( 3 0 0 0 ) ;

d i g i t a l W r i t e ( stepPinX , LOW) ;

delayMicroseconds ( 3 0 0 0 ) ;

}

(52)

APPENDIX B. ARDUINO CODE delay ( 1 5 0 0 ) ;

x≠=0.5;

}

void returnToStart (){

squareUp ( y ) ; squareRight (7≠x ) ; }

// Functions for the Hall≠e f f e c t sensor

// Function that read and re t ur n s the value given by the Hall≠e f f e c t sensor f l o a t readHall (){

d i g i t a l W r i t e ( electromagnetPin , HIGH) ; delay ( 2 0 0 ) ;

d i g i t a l W r i t e ( electromagnetPin , LOW) ; delay ( 3 0 0 ) ;

hallValue=analogRead ( hallSensorPin ) ;

} // Function that s t o r e s values given by the Hall≠e f f e c t sensor // input : the counter for the Hall≠sensor , and h a l l v a l u e i n t s t o r e H a l l (){

i n t row = x ; i n t c o l = y ;

i f ( hallValue >=818){ // white piece board1 [ row ] [ c o l ]=1;

} else i f ( hallValue <818 && hallValue >=800){// black piece board1 [ row ] [ c o l ]=2;

} else {//no detected piece board1 [ row ] [ c o l ]=0;

} }

// Functions used for the communication between the boards // Function that scans the board and maps the p i e c e s

i n t scanBoard (){

returnToStart ( ) ; while (y<=7){

readHall ( ) ; s t o r e H a l l ( ) ; i f ( x==7){

while (x>0){

40

(53)

squareLeft ( 1 ) ; readHall ( ) ; s t o r e H a l l ( ) ; }

} else {

while (x<7){

squareRight ( 1 ) ; readHall ( ) ; s t o r e H a l l ( ) ; }

} i f ( y!=7){

squareDown ( 1 ) ; } else {

break ; }

} returnToStart ( ) ; }

// Function that checks for discrepancy . // Returns true i f found , false otherwise

// I f player i s 1 we look for discrepancy in order to // know what c o o r d i n a t e s to upload to the s e r v e r // otherwise look for discrepancy to know the // c o o r d i n a t e s from the opponents move

void discrepancy ( i n t player ){

for ( i n t i ; i <5; i ++){

cArray [ i ] = 0 ; // Reset the comparison array } for ( i c =0; ic <=7; i c ++){

for ( j c =0; jc <=7; j c ++){

i f ( player == 1){

i f ( ( board1 [ i c ] [ j c ] == 0) && ( board2 [ i c ] [ j c ] !=0)){

cArray [ 0 ] = 1 ; // Discrepancy found cArray [ 1 ] = j c ; //xFrom

cArray [ 2 ] = i c ; //yFrom

} else i f ( board1 [ i c ] [ j c ]≠board2 [ i c ] [ j c ] != 0){

cArray [ 3 ] = j c ; //xTo

cArray [ 4 ] = i c ; //yTo

}

(54)

APPENDIX B. ARDUINO CODE } else {

i f ( ( board2 [ i c ] [ j c ] == 0) && ( board1 [ i c ] [ j c ] !=0)){

cArray [ 0 ] = 1 ; // Discrepancy found cArray [ 1 ] = j c ; //xFrom

cArray [ 2 ] = i c ; //yFrom

} else i f ( board2 [ i c ] [ j c ]≠board1 [ i c ] [ j c ] != 0){

cArray [ 3 ] = j c ; //xTo cArray [ 4 ] = i c ; //yTo }

} } }

} // Function that counts and compares the number of p i e c e s on each board , // r e t u r n s 1 i f the same number , else 0

boolean sameNOP(){

// Counters used to s t o r e the number of p i e c e s on each r e p s e c t i v e board i n t nop1=0; // Number of pieces , board1

i n t nop2=0;

i n t comp ;

for ( i c =0; ic <=7; i c ++){

for ( j c =0; jc <=7; j c ++){

i f ( board1 [ i c ] [ j c ]!=0){

nop1+=1;

} }

} for ( i c =0; ic <=7; i c ++){

for ( j c =0; jc <=7; j c ++){

i f ( board2 [ i c ] [ j c ]!=0){

nop2+=1;

} }

} comp=nop2≠nop1 ; i f (comp==0){

return 1 ; } else {

return 0 ; }

}

42

(55)

// Functions for playing

// Function that moves the p o s i t i o n to the d e s i r e d p o s i t i o n / t a r g e t void moveToTarget (){

i f (y<yTarget ){

squareDown ( yTarget≠y ) ; } else {

squareUp (y≠yTarget ) ; } i f (x<xTarget ){

squareRight ( xTarget≠x ) ; } else {

squareLeft (x≠xTarget ) ; }

}

// Function that removes captured p i e c e void removePiece (){

xTarget = cArray [ 3 ] ; // xTo yTarget = cArray [ 4 ] ; // yTo moveToTarget ( ) ;

readHall ( ) ;

d i g i t a l W r i t e ( electromagnetPin , HIGH) ; i f (y>3){

halfSquareUp ( ) ; } else i f (y<=3){

halfSquareDown ( ) ;

} i f ( hallValue >512 && hallValue <545){

squareLeft ( x ) ; h a l fS q u a r e L e f t ( ) ;

d i g i t a l W r i t e ( electromagnetPin , LOW) ; halfSquareRight ( ) ;

} else i f ( hallValue >545){

squareRight (7≠x ) ; halfSquareRight ( ) ;

d i g i t a l W r i t e ( electromagnetPin , LOW) ; h a l fS q u a r e L e f t ( ) ;

} halfSquareUp ( ) ;

}

(56)

APPENDIX B. ARDUINO CODE

// Function that changes the p o s i t i o n of a piece , help≠function void movePiece (){

d i g i t a l W r i t e ( electromagnetPin , HIGH) ; i f ( xTarget>=x ){

halfSquareRight ( ) ; } else {

h a lf S q u a r e L e f t ( ) ; }

i f (y>=yTarget ){

squareUp (y≠yTarget ) ; halfSquareUp ( ) ; } else {

squareDown ( yTarget≠y ) ; halfSquareDown ( ) ; } i f ( xTarget>=x ){

halfSquareRight ( ) ; } else {

h a l fS q u a r e L e f t ( ) ; } i f (x>=xTarget ){

squareLeft (x≠xTarget ) ; } else {

squareRight ( xTarget≠x ) ; } i f (y>yTarget ){

halfSquareUp ( ) ; } else {

halfSquareDown ( ) ;

} d i g i t a l W r i t e ( electromagnetPin , LOW) ;

}

// Function that move p i e c e to i t s new l o c a t i o n

44

(57)

void moveToNew(){

yTarget = cArray [ 2 ] ; // yFrom xTarget = cArray [ 1 ] ; // xFrom moveToTarget ( ) ;

yTarget = cArray [ 4 ] ; // yTo xTarget = cArray [ 3 ] ; // xTo movePiece ( ) ;

returnToStart ( ) ;

memcpy( board1 , board2 , s i z e o f ( board2 ) ) ; }

// Function that move the p i e c e d i f f e r e n t l y depending on i f sameNOP void opponentsMove (){

boolean same = sameNOP ( ) ;

i f ( same==0){ // The opponent captured a piece removePiece ( ) ;

moveToNew ( ) ; } }

// Gets the boardstate and i f i t i s the Arduino ’ s turn from the website // Returns true i f it ’ s the Arduinos turn

boolean getData (){

getConnection ( ) ;

String getData = ”GET /ardCheck . php” ; // The webpage containing the data // Prepare the s e r v e r for the amount of bytes sent ;

sendCommand( ”AT+CIPSEND=0,”

+String ( getData . length ()+2) ,4 , ”>” ) ;

// This command can not be sent with sendCommand as // i t w i l l not save the response

esp8266 . p r i n t l n ( getData ) ; i n t i = 0 ;

String temp ;

// Allow the esp8266 some time to send and record response while ( i <5000){

i f ( esp8266 . a v a i l a b l e () >0){

temp=esp8266 . readString ( ) ;

} else {

(58)

APPENDIX B. ARDUINO CODE i +=1;

} }

//The values from the s e r v e r s t a r t s at index 49 , // i t contains one value for player and 64 for p i e c e s String data = temp . s u b s t r i n g (49 , 49+65);

i n t count = 0 ; // Used to parse through the data

//The f i r s t r e t u rn i n g value i s what player made the l a s t move , // 1 for Arduino , 2 for web browser , 0 for new game

i n t player = data . s u b s t r i n g ( count , count +1). toI nt ( ) ; count++;

//Goes through the r e s t of the data and saves the boardstate i t contains for ( i n t i c =0; ic <=7; i c ++){

for ( i n t j c =0; jc <=7; j c ++){

board2 [ i c ] [ j c ] = data . s u b s t r i n g ( count , count +1). t oI nt ( ) ; count++;

}

} // Closes the connection with the website and w i f i sendCommand( ”AT+CIPCLOSE=0” ,5 , ”OK” ) ;

sendCommand( ”AT+CWQAP” ,5 , ”OK” ) ; i f ( player != 1){

return true ; } else {

return false ; }

}

// Sends a recorded move to the website

// Parameters are the c o o r d i n a t e s of the recorded move void sendData ( i n t xFrom , i n t yFrom , i n t xTo , i n t yTo ){

getConnection ( ) ;

String xFromStr = convertASCII (xFrom ) ; String xToStr = convertASCII (xTo ) ;

yFrom += 1 ; // database has values from 1≠8 instead of 0≠7 yTo +=1;

String getData = ”GET / update . php? xfrom=’”+xFromStr

+” ’&yfrom=”+yFrom+”&xto=’”+xToStr+” ’&yto=”+yTo+”&player=1” ;

46

(59)

// Prepares the s e r v e r for the amount of bytes sent ;

sendCommand( ”AT+CIPSEND=0,” +String ( getData . length ()+2) ,4 , ”>” ) ; esp8266 . p r i n t l n ( getData ) ; // Sends the data to the website delay ( 1 5 0 0 ) ;

// Closes the connection with the website and w i f i sendCommand( ”AT+CIPCLOSE=0” ,5 , ”OK” ) ;

sendCommand( ”AT+CWQAP” ,5 , ”OK” ) ; }

// E s t a b l i s h e s a connection between the s e r v e r and Arduino void getConnection (){

// Sets the esp8266 in c l i e n t mode sendCommand( ”AT+CWMODE=1” ,5 , ”OK” ) ; // Get a connection with the w i f i

sendCommand( ”AT+CWJAP=\””+AP+”\” ,\ ””+PASS+”\”” ,20 , ”OK” ) ; // Ready the esp8266 to accept connections

sendCommand( ”AT+CIPMUX=1” ,5 , ”OK” ) ; // Get a connection with the s e r v e r

sendCommand( ”AT+CIPSTART=0,\”TCP\” ,\ ””+HOST+”\” , ”+PORT,15 , ”OK” ) ; }

// Sends AT commands through the esp8266 //command i s the AT command to be executed ,

// maxTime i s the maximum time i t i s allowed b e f o r e the // command f a i l s , response i s the expected response // from the esp8266 i f the command succeeds

void sendCommand( String command, i n t maxTime , char response [ ] ) { i n t counter = 0 ;

//some commands take some time b e f o r e a response i s sent while ( counter < (maxTime 1)){

esp8266 . p r i n t l n (command) ;

// i f the s u c c e s s f u l l message i s read , return i f ( esp8266 . f i n d ( response )){

break ; } counter++;

} }

// Converts a coordinate i n t o a ASCII charachter // A 0 get converted to ’ a ’ , 1 to ’b ’ etc .

String convertASCII ( i n t coo ){

References

Related documents

In one of the most extensive studies on the topic, Slavin (1990) looked at the effects of tracking across the curriculum, incorporating numerous smaller inquiries to study

Although ultrasonic pretreatments had a positive effect on the methane yield of most substrates with the highest obtained with sugar beets/sugar beet leaves and maize

Although neutron images can be created on X-ray film by using a converter, digital methods have been increasingly used in recent years The advantages of digital methods are used

I made the negative mold from the real plastic bag that I filled with products and groceries.. I chose the thin transparent bag because I needed to have it as thin as

In light of increasing affiliation of hotel properties with hotel chains and the increasing importance of branding in the hospitality industry, senior managers/owners should be

In this thesis we investigated the Internet and social media usage for the truck drivers and owners in Bulgaria, Romania, Turkey and Ukraine, with a special focus on

Language register in different domains of mathematics, and its importance for different groups of 8th grade

The Ives and Copland pieces are perfect in this respect; the Ives demands three different instrumental groups to be playing in different tempi at the same time; the Copland,