Blog Forum Contact Us

low.js Tutorial: Control LED via Serial

Node.js has a nice module called repl, which implements a read-eval-print loop. It is used to show the prompt when calling Node.js with no arguments.

In this example we will create such a loop, add a toggle command to toggle the LED and tell low.js to present it through the UART to USB adapter of the microcontroller board.

Before you try this tutorial, please do the Blink LED tutorial first.

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 repl = require('repl');
let uart = require('uart');
let gpio = require('gpio');

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

let stream = new uart.UART({pinRX: 3, pinTX: 1, baud: 115200});
let replServer = repl.start({input: stream, output: stream, terminal: true, useColors: false});

replServer.defineCommand('toggle', () => {
    state = !state;
    gpio.pins[pinnumber].setValue(state);

    stream.write('LED toggled\n');
});

After syncing and starting the program, you can use a terminal program to connect to the microcontroller via UART/USB and the baud rate of 115,200 and toggle the LED by entering .toggle.

> .toggle
LED toggled
> 

Next tutorial: Even more...