Creating a TCP Client with NodeMCU Microcontroller in Station Mode

Sharad Regoti
2 min readJul 10, 2019

--

Initialize Variables

const char *ssid = "sharad";      // wifi router name
const char *pass = "aINl5jy9"; // wifi router password
const char *host = "10.42.0.156"; // server IP Address
const int port = 8000; // server port
int flag = 1; // flag to check for connection existance

Use the TCP Server android app to create a demo server then get the IP & port values from the app & make changes to the code accordingly.

Change the wifi router name & password in the code accordingly.

NOTE: Your Smart Phone Should be Connected to Same Wifi.

Setup

void setup(){  
Serial.begin(115200); // initialize serial communication
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA); // set mode to wifi station
WiFi.begin(ssid, pass); // connect to wifi router
while (WiFi.status() != WL_CONNECTED){ // check status of connection
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP()); // print the Ip alocated by router
delay(500);
}

Initialize the serial communication between Nodemcu & Computer for printing debugging messages.

Set the Nodemcu mode to Wifi Station mode then connect to Wifi router.

Wait while the connection status is not equal to WL_CONNECTED.

Loop

void loop() {  
if (flag == 1) { // if true means not connected to any server
if (client.connect(host, port)){ // connect to server
Serial.println("Connected to server");
flag = 0; // reflect the status of connection
}
}
else {
if (client.available()) { // check for incomming data from server
String dataFromServer = client.readStringUntil('\r'); Serial.println(dataFromServer);
}
if (client.connected()) { // check if connection exists
client.println((float(analogRead(A0) * 10)) / 1024); send data
}
else {
Serial.println("No server available disconnecting"); client.stop();
flag = 1;
}
}
delay(50);
}

If the flag is 1 indicating no connection with the server then try connecting to the server with given IP & Port values. After successful connection change the flag to 0.

If the server connection exists then check for incoming data from the server also send sensor data to the server.

If no connection then disconnect & change the flag to 1.

Github link of the full code

--

--

Sharad Regoti
Sharad Regoti

Responses (1)