-1

I had been working with Espruino for a bit and it is really a wonderful project. But, I am facing an issue for saving the code onto the flash, so that it can still be run when power is supplied to the board(NodeMCU), instead of the PC COM port. The code works completely fine until it is passed from the terminal. But, if I switch over the power supply it stops working. Also, I tried the save() and E.on('init',function(){}) but to no avail. It still doesn't create a web server. If someone could help out here it could be great! Thanks!

function main() {
  var http = require('http');
  var led = Pin(5);
  http.createServer(function (req, res) {
    var url = req.url;
    res.writeHead(200);
    if(url == "/on") {
      digitalWrite(led, 1);
      res.end("on");
    } else if(url == "/off") {
      digitalWrite(led, 0);
      res.end("off");
    } else {
      res.end('Lol');
    }
  }).listen(80);
}
E.on('init', function(){
  main();
});

Here's the code I wish to write to my flash for the IOT project I am working on

Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31

1 Answers1

0

After fiddling around with the documentation and crawling the scrambled web for almost a whole day I found out a solution myself. The issue ->

function main() {
  var wifi = require('Wifi');
  wifi.startAP("testing");
  wifi.save();
  var http = require('http');
  var led = Pin(5);
  return http.createServer(function (req, res) {
    var url = req.url;
    res.writeHead(200);
    if(url == "/on") {
      digitalWrite(led, 1);
      res.end("on");
    } else if(url == "/off") {
      digitalWrite(led, 0);
      res.end("off");
    } else {
      res.end('Lol');
    }
  }).listen(80);
}
function test() {
  console.log('Starting server');
  setTimeout(function() {
    var server = main();
    console.log(server);
  }, 5000);
}
E.on('init', function(){
 test();
});
save();

The problem was that the MCU couldnot get enough time to connect to the wifi before the command for http.createServer() is executed. Since, it cannot obtain the ip address for the MCU, thus it is unable to process the http.createServer() command. Hence, a timeout was necessary to process a delay before it's execution.

Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31
  • I wouldn't use a timeout, just keep checking if it's ready and proceed asap – dandavis Jul 04 '17 at 19:43
  • Yeah that's true. We could call the main function within the callback for wifi.connect("SSID",{password:"password"}, function() { main();}); And connect to wifi in E.On('init'); – Trishant Pahwa Jul 05 '17 at 05:42