Sunday, November 8, 2015

Arduino Sensors in Unity by using Node.js with Express.js



For this weekend hack,  we are building a 3D game with custom control input from an Arduino board.  Watch the video and use the code below to build it for yourself.

Arduino Wiring
Arduino Code
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    int amount = analogRead(0);
    Serial.println(amount);
    delay(30);
}

Node Libraries
Express - We use this for routing the web page to listen to a port. We could change this so that the user could pass in different routes to get multiple potentiometer values. 

SerialPort - This is a library used to read in the serial port data so node can parse it and put it on the web. 

Node Server Code
var express = require("express");
var app = express();
var serialPort = require("serialport");
var SerialPort = serialPort.SerialPort;
var currentSetting = 0;

 var sp =  new SerialPort("serial_port",{
    baudrate:9600,
    parser:serialPort.parsers.readline("\n")
 });

sp.on('open',function(){
    sp.on('data',function(data){
        console.log(data);
        currentSetting = data;
    });
});

app.get("/",function(request, response){
    response.send(currentSetting);
})

app.listen(portNumber);

Unity Code (javascript)
#pragma strict
private var locked = false;
private var currentSpeed = 0;

function Start () {
}

function Update () {
    transform.Translate(Vector3.left * Time.deltaTime * currentSpeed * -1);
    if (!locked)
    {
        locked = true;
        AcceleratorInput();
    }
}

function AcceleratorInput(){
    var www = WWW("http://127.0.0.1:10800/");
    yield www;
    currentSpeed = (parseFloat(www.text)/1024) * 50;
    locked = false;
}


That is all.  I hope you enjoyed this weekend hack!

Jeremy Skrdlant

No comments:

Post a Comment