Blog Forum Contact Us

low.js Example: Control LED via Website

Letting the user control the LED through a website the microcontroller serves is easy. It is just basic Node.JS programming.

Enter the following code into /index.js:

Is the example not working as expected?

Try checking the status with lowsync status.

To start or restart the program call lowsync start.

You can also check for any (error-) output by calling lowsync monitor and then fix any errors you find in your editor.

Remember to call lowsync sync after any changes you make.

let http = require('http');
let fs = require('fs');
let gpio = require('gpio');

let state = 0;
gpio.pins[pinnumber].setType(gpio.OUTPUT).setValue(state);

fs.readFile('/client.html', 'utf8', (err, page) => {
    if(err) {
        console.log(err);
        return;
    }

    http.createServer((req, res) => {
        if (req.url == '/Toggle') {
            res.end();
    
            state = !state;
            gpio.pins[pinnumber].setValue(state);
        } else if (req.url == '/') {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(page);
        } else {
            res.writeHead(404);
            res.end();
        }
    }).listen(80);
});

Enter the following code into /client.html. This file will be sent to the web browser.

<html>
    <head>
        <title>Example</title>
        <script type="text/javascript">
            function toggle() {
                var request = new XMLHttpRequest();
                request.open('GET', '/Toggle', true);
                request.send();
            }
        </script>
    </head>
    <body>
        <p>The example page, served by low.js</p>
        <p><input type="button" value="Toggle LED" onclick="javascript: toggle()"></p>
    </body>
</html>

Sync and restart program. You should see the website when pointing your web browser to the microcontroller's IP.