Arduino Playground is read-only starting December 31st, 2018. For more info please look at this Forum Post

Web server using AngularJS

This demo features a web server on the arduino that presents the values of the analog inputs as a JSON data packet, and a corresponding web page that reads and displays that data using AngularJS.

The web server reads and processes the HTTP headers, extracting the Content-Length (although it is not used). The AngularJS page extracts the array and displays it.

You may need to alter the mac, ip address, and port in the sketch. If you do, alter the $http.get('http://10.1.1.21:80') in the javascript.

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

byte mac[] = {
  // first byte DE, remaining bytes decided by d20 roll
    0xDE,  0xB2,  0x77,  0xA5,  0x21,  0x48
};

IPAddress ip(10, 1, 1, 21);

EthernetServer server(80);

void setup() {
    Ethernet.begin(mac, ip);
    server.begin();
}

const int MAXLN = 256;
char ln[MAXLN + 1];
int contentLength;

boolean readLine(EthernetClient &client) {
    int i = 0;
    boolean cr = false;

    for (;;) {
        if (!client.connected()) return false;
        if (!client.available()) continue;
        char c = client.read();
        switch (c) {
            case '\r':
                if (cr) {
                    // should never happen
                    if (i < MAXLN) ln[i++] = '\r';
                }
                cr  =  true;
                break;

            case '\n':
                if (cr) {
                    // there's always room for the trailing NUL
                    ln[i++]  =  '\0';
                    return true;
                }
                // else fall through, treat \n like a regular character
                // should never happen

            default:
                if (cr) {
                    // should never happen
                    if (i < MAXLN) ln[i++] = '\r';
                    cr  =  false;
                }
                if (i < MAXLN) ln[i++] = c;
                break;
        }
    }
}

boolean readRequestHeader(EthernetClient &client) {
    if(!readLine(client)) return false; // read the http request line

    contentLength  =  -1;  // initialize

    // we are assuming http 1.1. Read lines until we get a blank line
    do {
        if(!readLine(client)) return false; // read a header

        // pull out Content-Length, for example
        if(strncmp(ln, "Content-Length: ", 16) == 0) {
            contentLength  =  atoi(ln+16);
        }  
    }
    while (strlen(ln) > 0);
    return true;
}


void loop() {
    // is someone making a request?
    EthernetClient client = server.available();
    if (!client) return;

    if(!readRequestHeader(client)) {
        client.stop();
        return;
    }

    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: application/json");
    client.println("Connection: close");
    // this is the CORS header. Yery important. Google CORS.
    client.println("Access-Control-Allow-Origin: *");
    client.println();
    client.print("{\"analogInput\":[");
    for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
        if(analogChannel>0) client.print(',');
        int sensorReading = analogRead(analogChannel);
        client.print(sensorReading);
    }
    client.println("]}");

    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
}

<html>
<head>
<meta charset="UTF-8">
<title>Arduino JSON example client page</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script type="text/javascript">
var app = angular.module("readArduinoApp", []);

app.controller("ReadArduinoController", [ '$scope', '$http',
function($scope, $http) {
$scope.ok = false;
$scope.fetching = false;
$scope.status = "no data yet";

$scope.fetchOk = function onOk(response) {
$scope.data = response.data;
$scope.fetching = false;
$scope.ok = true;
};

$scope.fetchNotOk = function onOk(response) {
$scope.data = "Not OK: " + JSON.stringify(response);
$scope.fetching = false;
$scope.ok = false;
};

$scope.fetch = function() {
$scope.fetching = true;
$http.get('https://10.1.1.21:80').then(
$scope.fetchOk,
$scope.fetchNotOk
);
};

$scope.fetch();
}
]
);
</script>

</head>
<body ng-app="readArduinoApp">
<div ng-controller="ReadArduinoController">
<div ng-if="ok" ng-repeat="reading in data.analogInput track by $index">
Analog input A{{$index}} is {{reading}} 
</div>
<div ng-if="!ok">{{status}}</div>
<div ng-if="fetching">Fetching ...</div>
<div ng-if="!fetching">
<button ng-click="fetch()">Fetch</button>
</div>
</div>
</body>
</html>