Thursday, January 29, 2015

Publishing sketch values on a web page hosted by the Yun

This is a simple way to get values from the sketch made visible to a browser that can connect to the Yun.
The Arduino Yun wil be used as leightweight webserver.
The sketch just puts the values in the Bridge, the webserver reads them from there.

I am using "bottle" as example webserver.

Sketch code:

/* vim: set filetype=cpp: */
#include 

void setup()
{
  Bridge.begin();
}

void loop()
{

    char value[40];  // 40 is probably too much
    uint32_t my_time;
    uint32_t my_random;

    while(true)
    {
       my_time=millis();
       my_random=random(99);

       ultoa(my_time,value,10);
       Bridge.put("TIME",value);
       ultoa(my_random,value,10);
       Bridge.put("RAND",value);

       delay(1000);
    }

}

Python code:

#!/usr/bin/python

import sys
from bottle import run, route, get, post, request

sys.path.insert(0, '/usr/lib/python2.7/bridge/')
from bridgeclient import BridgeClient as bridgeclient
bc = bridgeclient()

@route('/status')
def status():
    try:
        t =  bc.get("TIME")
        r =  bc.get("RAND")
        return "Time="+t+"
 Rand="+r
    except:
        return "Oops\n"

def main():

    run(host='0.0.0.0', port=48964, debug=True)

if __name__ == '__main__':
    main()


After starting the python code on the linux side you can browse to http://arduino.local:48964/status and get: