简体   繁体   中英

Raspberry Node-js GPIO control

I want to turn the LED on GPIO4 with the button on. But nothing happens. The log would display nothing. I think i failed to open the function or to write the function.

var http = require('http');
var Gpio = require('onoff').Gpio;

var LED = new Gpio(4, 'out');


var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<button onclick="LEDon()">ON</button>');
    res.write('<button onclick="LEDoff()">OFF</button>');
    function LEDon(){
        LED.writeSync(1);
        console.log('1');
    }
    
    function LEDoff(){
        LED.writeSync(0);
        console.log('2');
    }
  res.end();
}).listen(8080);

Hello and welcome to SO,

Try this:

var http = require('http');
var HttpDispatcher = require('httpdispatcher');
var Gpio = require('onoff').Gpio;

var dispatcher = new HttpDispatcher();

var LED = new Gpio(4, 'out');

function handleRequest(request, response){
    try {
        // log the request on console
        console.log(request.url);
        // Dispatch
        dispatcher.dispatch(request, response);
    } catch(err) {
        console.log(err);
    }
}  

dispatcher.onGet('/', function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(`
        <form action="/on" method="post">
            <input type="submit" value="On" />
        </form>
    `);


    res.write(`
        <form action="/off" method="post">
            <input type="submit" value="Off" />
        </form>
    `);
});

dispatcher.onPost('/on', function(req, res) {
    LED.writeSync(1);
    console.log('1');
});

dispatcher.onPost('/off', function(req, res) {
    LED.writeSync(0);
    console.log('2');
});

http.createServer(handleRequest).listen(8080);

You will also need to install the httpdispatcher package by running npm i httpdispatcher --save

The reason for your code not working is because you are trying to call functions in node through your browser which is not possible directly, so here we do it through some forms and post calls to the HTTP server which then triggers your GPIO functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM