Arduino Websockets tutorial

In this tutorial, we’ll hook up an Arduino to a dizmo using WebSockets.

Parts needed

Arduino Ethernet: https://store.arduino.cc/product/A000068
Serial to USB Adaptor: https://www.sparkfun.com/products/9716
Arduino Uno R3: http://www.adafruit.com/products/50
Arduino Ethernet Shield: https://www.arduino.cc/en/Main/ArduinoEthernetShield

We need an Arduino that can connect to a network. Either an Arduino with an Ethernet Shield, or as we are using, an Arduino Ethernet. To program the Arduino Ethernet, you’ll need to use the Serial to USB Adapter, if you are using an Arduino Uno (or similar) it will usually have a Serial to USB Adapter integrated.

Arduino Library Installation

Our Arduino Code needs a library to implement the Websocket Server. Download it from the Github repository:

Arduino-WebsocketServer https://github.com/ejeklint/ArduinoWebsocketServer

Install the library by following this guide: ttps://learn.sparkfun.com/tutorials/installing-an-arduino-library

WebSocket Server Arduino Code

Open the Arduino IDE and paste the following code:

#include <SPI.h>
#include <Wire.h>
#include <Ethernet.h>

// Enabe debug tracing to Serial port.
#define DEBUG true
#define STATICIP false

byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x91, 0x8C }; // adjust to the MAC Address of your Arduino Ethernet/Ethernet Shield

#if STATICIP
byte ip[] = {10,0,1,100};
#endif

// Create a Websocket server
WebSocketServer wsServer;

void onConnect(WebSocket &socket) {
  Serial.println("onConnect called");
}

// You must have at least one function with the following signature.
// It will be called by the server when a data frame is received.
void onData(WebSocket &socket, char* dataString, byte frameLength) {

#ifdef DEBUG
  Serial.print("Got data: ");
  Serial.write((unsigned char*)dataString, frameLength);
  Serial.println();
#endif

  // Just echo back data for fun.
  socket.send(dataString, strlen(dataString));
}

void onDisconnect(WebSocket &socket) {
  Serial.println("onDisconnect called");
}

void setup() {
#ifdef DEBUG  
  Serial.begin(9600);
#endif

#if STATICIP
  Ethernet.begin(mac, ip);
#else
  if (Ethernet.begin(mac) == 0) {
#if DEBUG
    Serial.println("Unable to set server IP address using DHCP");
#endif
    for(;;)
      ;
  }
#if DEBUG
  // report the dhcp IP address:
  Serial.println(Ethernet.localIP());
#endif
#endif

  wsServer.registerConnectCallback(&onConnect);
  wsServer.registerDataCallback(&onData);
  wsServer.registerDisconnectCallback(&onDisconnect);  
  wsServer.begin();

  delay(100); // Give Ethernet time to get ready

 
}

void loop() {
  // Should be called for each loop.
  wsServer.listen();

  // Do other stuff here, but don't hang or cause long delays.
  delay(100);



    if (wsServer.connectionCount() > 0) {
      wsServer.send("HELLO", 5);
    }

}

Transfer the sketch to your Arduino and open the Serial Console. Note the IP-Address printed out there:

192.168.1.194

Websocket Client Dizmo

Now, we are going to implement the dizmo that connects to the Arduino via Websockets. Create a new dizmo project with grace:

grace new

Use the following parameters when asked by grace:

name: Websocket
type: dizmo
skeleton: default

Now, change to the new project directory:

cd Websocket

Edit the file src/index.html to add a textarea element, replacing the Hello World that is there already.

        <textarea id="msg" data-type="dizmo-textarea"></textarea>

Now, edit the file src/application.js and add the following code inside the dizmoreadyevent handler function:

window.document.addEventListener('dizmoready', function() {
    ws = new WebSocket("ws://<insert ip address from above>:80/");

    ws.onmessage = function(evt) {
        window.console.log(evt.data);
        document.getElementById("msg").innerHTML=evt.data;
    };
    ws.onerror = function(evt) {
        window.console.log(evt.data);
        document.getElementById("msg").innerHTML="ERROR: "+evt.$
    };
    ws.onclose = function() {
        window.console.log("onclose called");
    });
    ws.onopen = function() {
        window.console.log("onopen called");
        ws.send("Hello, Arduino");
    };
});

Build and zip the dizmo with grace

python manage.py zip

Drag the resulting file from the build folder into dizmoSpace