2

I would like to seek help on my Web Control Interface - LED On and OFF button REST API. I just started node.js two weeks ago and manage to created a basic REST API. It manage to display mySQL database records without any problems and I just created a button with the function of controlling GPIO directly and store to mySQL database. But when I start to run my app.js and click my ON button, my Red LED didn't light up and can't store to mySQL database.

Hope you guys could help me out with it as soon as possible, thanks in advance, guys.

This is my Button REST API main page screenshot:

enter image description here

This is my app.js:

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();

// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 3000);

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);

// Catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
var server = app.listen(app.get('port'), function() {
  console.log('Listening on port %d', server.address().port);
});

This is my /routes/index.js:

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var gpio = require('pi-gpio');

var conn = {
   host: 'localhost',
   user: 'user',
   password: 'password',
   database: 'rest_api',
   port: '3306'
};

router.get('/', function(req, res) {
   var connection = mysql.createConnection(conn);
   var query ='SELECT sensorId, sensor, pinNo, sensorType FROM sensorInfo';

   connection.query(query, function(err, rows, fields) {
          if (err) {
         throw err;
      }
      console.log(rows);
          res.render('index', { 
         title: 'Sensor Rest API', 
         data: rows
      });    
   });

});

router.post('pin7On', function() {
   var pin = req.params.pin;
   var connection = mysql.createConnection(conn);

   gpio.open(7, 'output', function(err) {
      gpio.write(7, 1, function(err) {
         connection.query('INSERT INTO sensorLog(sensorId, logTime, sensorValue) VALUES(1, current_timestamp(), 1)', function(err) {
            if (err) {
               throw err;
            } else {
               console.log("Successfully store to mySQL database");
            }
         });
         gpio.close(7);
      });
   });
});

router.post('pin7Off', function() {
   var pin = req.params.pin;
   var connection = mysql.createConnection(conn);

   gpio.open(7, 'output', function(err) {
      gpio.write(7, 0, function(err) {
         connection.query('INSERT INTO sensorLog(sensorId, logTime, sensorValue) VALUES(1, current_timestamp(), 0)', function(err) {
            if (err) {
               throw err;
            } else {
               console.log("Successfully store to mySQL database");
            }
         });
         gpio.close(7);
      });
   });
});

module.exports = router;

This is my /views/index.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1 align="center">
   <%= title %>
    </h1>
    <h3 align="center">
   Sensor Information Log
    </h3>
    <table border="1" cellpadding="2" cellspacing="2" align="center">
   <tr>
        <th>Sensor ID</th>
        <th>Sensor</th>
        <th>Pin Number</th>
        <th>Sensor Type</th>
   </tr>
   <% for(var i = 0; i < data.length; i++) { %>
      <tr align="center">
           <td><%= data[i].sensorId%></td>
           <td><%= data[i].sensor%></td>
           <td><%= data[i].pinNo%></td>
           <td><%= data[i].sensorType%></td>
      </tr>
   <% } %>
     </table>
     <br/>
     <h3 align="center">
   Web Control Interaface
     </h3>
     <table border="1" cellpadding="2" cellspacing="2" align="center">
   <tr>
        <th>Sensor</th>
        <th colspan="2">Control</th>
   </tr>
   <tr>
        <td>Red LED</td>
        <td><input type="button" id="pin7On" value="ON"></td>
            <td><input type="button" id="pin7Off" value="OFF"></td>
   </tr>
     </table>
     <script>
   $('#pin7On').click(function() {
          $.ajax({
              pin7On,
              method: 'POST'
          });
   });
   $('#pin7Off').click(function() {
          $.ajax({
              pin7Off,
              method: 'POST'
          });
   });
     </script>
  </body>
</html>
  • are you running node as root? "sudo node myprog.js" – rob Aug 6 '14 at 8:21
  • Nope, rob. I running as pi and just node app.js, rob – user3127380 Aug 6 '14 at 12:34
  • have you tried it with sudo? – rob Aug 6 '14 at 13:52
  • What is the console output? Also, have you installed gpio-admin. That is the preferred method. You shouldn't run node as root. – Gerben Aug 6 '14 at 15:11
  • rob: I tried already but still light up and can't store to mySQL database. Gerben: I never install gpio-admin and I'm running as pi instead of root. – user3127380 Aug 7 '14 at 1:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.