Connect NodeMCU to Server

Introduction

Hello everyone, this another post on NodeMCU. In this post, I am going to write about how to connect and send the request from your esp client to the server. If you have little idea about NodeMcu or Esp8266, you can go back to previous posts. Let’s get started.

Prerequisite

Hardware

Software

The Project

In this project, I am going to read the data from the temperature sensor from ADC, and send that data to the local server running on my computer. Of course, the NodeMCU and the computer need to be in the same network.

I am hoping that you guys have Node.js installed in your system. If not, then go ahead and install it because we are going to create server using this. Now that you have done that, let’s create a server.

The Server

Create a folder in your desired location. Open the terminal or command prompt in that location and type-npm init and keep pressing enter. After this is done, type “npm install express”. This is going to install the express module that we are going to use. That’s all we needed, let’s do some coding.

I hope you have some idea about node.js. If you don’t, please familiarise yourself with it. Here’s the code of server written in node.

var express = require('express');
 var app = express(); 
var bodyParser = require('body-parser') 
app.get('/', function (req, res) { 
res.send("Hello from Server"); 
}) 
app.use(bodyParser.urlencoded({ extended: false })) 
app.post('/', function(req, res) { res.send('Got the temp data, thanks..!!');
console.log(JSON.stringify(req.body));
}) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example server listening at localhost:%s", host, port)
})

The server is listening at your machine’s IP address and the port is 8081. Here I am telling server what to do when any of the “get” or “post” request comes. The function “console.log” use to print anything to the prompt. The function “JSON.stringify” converts the objects to string and this line “app.use(bodyParser.urlencoded({ extended: false }))” is parsing the temperature data from the request.

Run the above code in your machine by going to the directory from the command prompt or terminal, and type node FILENAME.js

The Client-NodeMCU

I have used the esp8266 library for this. If you don’t know how to do that, follow this tutorial. As the nodeMCU has an ADC, I can directly interface the temperature sensor to it. I am using the temperature sensor present in the groove kit. Just connect the signal pin of the temperature sensor to your ADC pin, connect Vcc and ground and you are good to go. If you are very beginner and don’t know about the interfacing of a temperature sensor, well you can follow this link.

#include <ESP8266WiFi.h>

const char* ssid     = "WifiName";
const char* password = "YourPassword";

const char* host = "IP";

# define sensorPin A0
const int R0 = 100000; 
const int B = 4275;   

void setup() {
pinMode(sensorPin, INPUT);

  
  Serial.begin(115200);
  delay(10);
  pinMode(A0, INPUT);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


void loop() {
 delay(5000);
int val = analogRead(sensorPin);
float R = 1023.0/val-1.0;
R = R0*R;
float temperature = 1.0/(log(R/R0)/B+1/298.15)-273.15;
 Serial.print("connecting to ");
 Serial.println(host);

 // Use WiFiClient class to create TCP connections
 WiFiClient client;
 const int httpPort = 8081;
 if (!client.connect(host, httpPort)) {
  Serial.println("connection failed");
  return;
 }

 // We now create a URI for the request
 String url = "/";

 Serial.print("Requesting URL: ");
 Serial.println(url);
String data = "temperature=" + String(temperature);

   Serial.print("Requesting POST: ");
   // Send request to the server:
   client.println("POST / HTTP/1.1");
   client.println("Host: server_name");
   client.println("Accept: */*");
   client.println("Content-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.println(data.length());
   client.println();
   client.print(data);
 // This will send the request to the server
 /*this is a get method working
  * client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Connection: close\r\n\r\n");*/
 unsigned long timeout = millis();
 while (client.available() == 0) {
 if (millis() - timeout > 5000) {
  Serial.println(">>> Client Timeout !");
  client.stop();
  return;
 }
}

 // Read all the lines of the reply from server and print them to Serial
 while(client.available()){
  String line = client.readStringUntil('\r');
  Serial.print(line);
 }

 Serial.println();
 Serial.println("closing connection");
}

 

The above code first connects with the “wifi” and send the temperature data to the server. There are some things you would need in order to run this code. Enter the SSID of your network and along with the password and enter the IP address of the machine on which server is running. To know the IP address, just type “ipconfig” of the command prompt admin of your windows computer and “ifconfig” in your Linux computer.

The code is pretty much straight forward. It first connects with the Wifi, reads the data from the temperature sensor and send it to the server and then wait for 5 seconds.

Execution of the program

Open up the serial terminal after burning the program to NodeMCU. You are going to see the logs there. On the server console, if everything works fine you are going to see the temperature data there.

If you have any doubts or feedback, please write it down in the comment section. Do check out the other posts as well.

3 thoughts on “Connect NodeMCU to Server”

  1. I tried writing the reading to a local html file using response.write() under the app.post() method but it did not work. Any suggestions?

  2. Get method not working .
    client.print(String(“GET http://192.168.0.888:5555/project“) +
    (“/”) + temperature +
    (“/”) + humidity +
    ” HTTP/1.1\r\n” +
    “Host: ” + host + “\r\n” +
    “Connection: close\r\n\r\n”);
    unsigned long timeout = millis();
    while (client.available() == 0) {
    if (millis() – timeout > 1000) {
    Serial.println(“>>> Client Timeout !”);
    client.stop();
    return;
    }
    }

Leave a Comment

Your email address will not be published. Required fields are marked *

Share This