loading...
Wia

Play Rock Paper Scissors Using the ESP8266

anspivey profile image Austin Spivey ・5 min read

alt text
In this tutorial, we will build an online rock, paper, scissors game using ESP8266, the Wia Dashboard, and Github.

What You Will Need

  • 2x ESP8266
  • 2x Micro USB to USB cables

Before you begin, you must have a Wia account. You can create one here.

If you have not set up your ESP8266 with Arduino yet, you will need to do that first. This tutorial will show you how.

Getting Started

First, connect a USB cable to one of the ESP8266 and plug it into your computer or laptop.

Open the Arduino IDE. You can download the latest version here. In Arduino IDE, create a new sketch and save it as playerOne.ino. Create a second sketch and name it playerTwo.ino.

Next, navigate to the Wia Dashboard, create a new space and add device. Name it something like "playerOne".

alt text

Once you have added your device, navigate to the Devices tab on the left-hand side of the page. Select your device, then navigate to the configuration tab. You will see your device ID as well as your device_secret_key. You will need need to device secret key later.

The Code

Copy and paste the following code into your Arduino sketch named playerOne.ino.


#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

const char* ssid     = "name-of-your-Wifi";
const char* password = "your-Wifi-Password";

// get this from the wia dashboard. it should start with `d_sk`

const char* device_secret_key = "your-device-secret-key";

boolean buttonState = HIGH;
boolean buttonDown = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(0, INPUT);
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP(ssid, password);
}

void loop() {
  // put your main code here, to run repeatedly:
  buttonState = digitalRead(0);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is LOW:
  if (buttonState == LOW) {
    if (buttonDown == false) {
      Serial.println("Button Pushed");
      buttonDown = true;
      postToWia();
      delay(750);
    }
  } else {
    buttonDown = false;
  }
}

void postToWia() {
  // wait for WiFi connection
  if((WiFiMulti.run() == WL_CONNECTED)) {
    HTTPClient http;
    USE_SERIAL.print("[HTTP] begin...\n");
    // configure wia rest api
    http.begin("http://api.wia.io/v1/events");
    USE_SERIAL.print("[HTTP] POST...\n");

    // set authorization token
    http.addHeader("Authorization", "Bearer " + String(device_secret_key));
    // set content-type to json
    http.addHeader("Content-Type", "application/json");
    // start connection and send HTTP headers. replace name and data values with your own.
    int httpCode = http.POST("{\"name\":\"buttonPress\"}");
    // httpCode will be negative on error

    if(httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        USE_SERIAL.printf("[HTTP] POST... code: %d\n", httpCode);
        // file found at server
        if(httpCode == HTTP_CODE_OK) {
            String payload = http.getString();
            USE_SERIAL.println(payload);
        }
    } else {
        USE_SERIAL.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
  }
}

Change the following values:

  • name-of-your-WiFi to the name of your WiFi. This must be the same WiFi network that your computer is using.
  • your-WiFi-password to your WiFi network password

  • you-device-secret-key to your device secret key, found on the Wia Dashboard under Devices > Configuration

Upload the code to your device by clicking upload in the Arduino IDE. Then, set your device aside. Remember that this device is playerOne and contains the playerOne code.

Connect the second device to your computer, and add it to your space in the Wia Dashboard. This device will have an entirely different device-secret-key. Collect the key from the configuration tab. Copy and paste the code from before into the Arduino file playerTwo.ino, but change the device-secret-key to match the second device.

Upload the code from the file playerTwo.ino onto your second device.

Wia Flows

Now in your Wia dashboard, click Flows in the left-hand sidebar. Create a new flow and name it whatever you like.

Drag over an Event from the trigger tab and name it buttonPress. Select both devices.

alt text

In the logic tab, drag over a run-function node. Drag the yellow dot from the Event node to the run-function node. In the box, copy and paste this code:

  var items = [
    'πŸ—Ώ',
    'πŸ“œ',
    'βœ‚'
];

var item = items[Math.floor(Math.random()*items.length)];
output.body.data = item;

Your screen should look like this:

alt text

Click Update.
Then, in the action tab, drag over an event and name it emoji. To connect the nodes, drag the orange dots. Your screen should look like this:

alt text

Next, navigate to Devices > playerOne. This should take you to the overview page for your device. In the right hand corner, click add a widget. Write emoji for the title and emoji for the event. Then, navigate back to Devices on the sidebar and select your device for playerTwo. Create a new widget and write emoji for the title and emoji for the event.

alt text

Plug both devices into your computer. Press the flash button on both devices. Your widgets will show whether the device chose rock, paper or scissors.

However, navigating between the two devices is not an efficient way to play the game. So, we must make a webpage that will show us the result of each player's choice simultaneously.

To do this, we will use Github. You can create an account here.

Web Page

Begin by logging into Github. Create a new repository and name it your-github-username.github.io. Check the box to initialize with a README.

Once you have created your respository, open it. Click create new file. Copy and paste the code below into a file called index.html. The file must be named index.html.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Wia Game</title>
  </head>
  <body>
    <h1>Wia Rock Paper Scissors</h1>
  </body>
</html>

This is the HTML boilerplate. To see our game update in real time, we need to embed our widgets from Wia. Back in the Wia Dashboard, navigate to one of the two player devices. In the overview, you can see your widget. Click the box with an arrow in the upper right hand corner of the widget. Choose the setting anyone can view this widget. Copy the code of embed the widget. The code starts with and ends with .

Back in GitHub, edit the index.html file. Paste the widget code below the header <h1>Wia Rock Paper Scissors</h1>.

Repeat this with the widget for the other device. Now, your HTML file should look like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Wia Game</title>
  </head>
  <body>
    <h1>Wia Rock Paper Scissors</h1>
    <iframe> YOUR WIDGET </iframe>
    <iframe> YOUR SECOND WIDGET </iframe>
  </body>
  </html>

To view your new Web Page, navigate to https://your-github-username.github.io/

And there is your game!

Posted on by:

anspivey profile

Austin Spivey

@anspivey

Tourist in a Tutu || Chicago Born || Melbourne/Mexico/California Raised || New Yorker at Heart || SF to Dublin to work for Wia the best #IoT startup

Wia

Wia is where people and things go to talk. Our mission is to make it possible for anyone to connect anything to the Internet, creating the next generation of the physical web. Developers across the world use Wia to build out IoT Solutions.

Discussion

pic
Editor guide