My GPS U-blox NEO6M is returning NULL continuously instead of lat, long values - geolocation

I have interfaced my ESP32 with a ublox GPS tracker NEO-6M module. It is continuously printing NULL on the serial monitor and even after 10 to 15seconds it prints NULL. What could be the possible reason and how to rectify that?
Here is the code:
#include <TinyGPSPlus.h>
// The TinyGPSPlus object
TinyGPSPlus gps;
void displayInfo()
{
Serial.print(F("Location: "));
if (gps.location.isValid()){
Serial.print("Lat: ");
Serial.print(gps.location.lat(), 6);
Serial.print(F(","));
Serial.print("Lng: ");
Serial.print(gps.location.lng(), 6);
Serial.println();
}
else
{
Serial.print(F("INVALID"));
}
}
void updateSerial()
{
// delay(500);
while (Serial.available())
{
Serial2.write(Serial.read());//Forward what Serial received to Software Serial Port
}
while (Serial2.available())
{
Serial.write(Serial2.read());//Forward what Software Serial received to Serial Port
}
}
void setup() {
Serial.begin(9600);
Serial2.begin(9600);
delay(3000);
}
void loop() {
updateSerial();
while (Serial2.available() > 0)
if (gps.encode(Serial2.read()))
displayInfo();
if (millis() > 5000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
while (true);
}
}

Thanks all for your support. I have found the answer. The GPS-NEO6M tracker works in open air environment not indoor or basement area. So I have used this code, gave it 5V power using Arduino UNO and still it was not connected to the satellite but as soon as I took it to the open air keeping the tracker position towards the sky, it started showing date and time and showed GPS coordinates in 3 to 4 minutes. The code that I used and is working finally is shown below:
#include<TinyGPS++.h>
#include<SoftwareSerial.h>
// Choose two Arduino pins to use for software serial
int RXPin = 16;
int TXPin = 17;
int GPSBaud = 9600;
// Create a TinyGPS++ object
TinyGPSPlus gps;
// Create a software serial port called "gpsSerial"
SoftwareSerial gpsSerial(RXPin, TXPin);
void displayInfo() {
if (gps.location.isValid()) {
Serial.print("Latitude: ");
Serial.println(gps.location.lat(), 6);
Serial.print("Longitude: ");
Serial.println(gps.location.lng(), 6);
Serial.print("Altitude: ");
Serial.println(gps.altitude.meters());
} else {
Serial.println("Location: Not Available");
}
Serial.print("Date: ");
if (gps.date.isValid()) {
Serial.print(gps.date.month());
Serial.print("/");
Serial.print(gps.date.day());
Serial.print("/");
Serial.println(gps.date.year());
} else {
Serial.println("Not Available");
}
Serial.print("Time: ");
if (gps.time.isValid()) {
if (gps.time.hour() < 10) Serial.print(F("0"));
Serial.print(gps.time.hour());
Serial.print(":");
if (gps.time.minute() < 10) Serial.print(F("0"));
Serial.print(gps.time.minute());
Serial.print(":");
if (gps.time.second() < 10) Serial.print(F("0"));
Serial.print(gps.time.second());
Serial.print(".");
if (gps.time.centisecond() < 10)
Serial.print(F("0"));
Serial.println(gps.time.centisecond());
} else {
Serial.println("Not Available");
}
Serial.println();
Serial.println();
delay(1000);
}
void setup() {
// Start the Arduino hardware serial port at 9600 baud
Serial.begin(9600);
// Start the software serial port at the GPS's default
//baud
gpsSerial.begin(GPSBaud);
}
void loop() {
// This sketch displays information every time a new
//sentence is correctly encoded.
while (gpsSerial.available() > 0)
if (gps.encode(gpsSerial.read()))
displayInfo();
// If 5000 milliseconds pass and there are no
//characters coming in
// over the software serial port, show a "No GPS
//detected" error
if (millis() > 5000 && gps.charsProcessed() < 10) {
Serial.println("No GPS detected");
while (true);
}
}

Related

ESP8266 WeMos D1 using deepsleep drains too much battery

I've developed a fingerprint sensor using NodeMCU D1 mini powered by a 1000mah battery.
Everything seems working correctly except for battery energy consumption.
I have read several topic where user says that using deepsleep fuction on NodeMCU 1000mah battery should last more than 3 month but mine doesn't reach 2 days.
This is my circuit schematic
I also report here my code snipped that I'm currently using. The circuit should wake up from deepsleep when the button is pressed and start reading the fingerprint sensor. If it detect a valid fingerprint, a message is sent to MQTT broker.
#include <Adafruit_Fingerprint.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* _ssid = "ZZZXXXYYY";
const char* _password = "pass";
const char* mqttServer = "IPADDRESS";
const int mqttPort = 1883;
const char* mqttUser = "USER";
const char* mqttPassword = "PASS";
long initialMillis = 0;
unsigned int raw=0;
// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
//#define mySerial Serial
// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino (WHITE wire)
// comment these two lines if using hardware serial
SoftwareSerial mySerial(4, 5);
WiFiClient espClient;
PubSubClient client(espClient);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
void setup()
{
Serial.begin(9600);
pinMode(A0, INPUT);
// Connect to Fingerprint. Set the data rate for the sensor serial port
finger.begin(57600);
delay(5);
if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :(");
ESP.deepSleep(10 * 1000000);
}
finger.getTemplateCount();
// Connect to WIFI
WiFi.mode(WIFI_STA);
WiFi.begin(_ssid, _password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Connect to MQTT
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESPFingerprint", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT server");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// Calculate battery percentage
raw = analogRead(A0);
String bLevel = "{\"Battery\":" + String(raw) + "}";
Serial.print("Battery: ");
Serial.print(raw);
Serial.print(" -> ");
Serial.println(bLevel);
initialMillis = millis();
client.publish("tele/fingerprint/LWT", "Online");
client.publish("tele/fingerprint/STATE", (char*)bLevel.c_str(), true);
Serial.print("MQTT subscribed: ");
Serial.println(WiFi.localIP());
}
void loop()
{
unsigned long currentMillis = millis();
int fid = getFingerprintIDez();
if(fid != -1) {
String fpIdstr = String(fid);
client.publish("cmnd/fingerprint/RESULT", (char*)fpIdstr.c_str());
Serial.println("Fingerprint correct. Going to sleep.");
client.publish("tele/fingerprint/LWT", "Offline");
// trigger disconnection from MQTT broker to correctly send the message before going to sleep
client.disconnect();
espClient.flush();
// wait until connection is closed completely
while(client.state() != -1){
delay(10);
}
ESP.deepSleep(0);
}
else if(currentMillis - initialMillis >= 15000){
Serial.println("Timeout expired. Going to sleep.");
client.publish("tele/fingerprint/LWT", "Offline");
ESP.deepSleep(0);
}
delay(50); //don't ned to run this at full speed.
}
uint8_t getFingerprintID() {
uint8_t p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println("No finger detected");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK success!
p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK converted!
p = finger.fingerFastSearch();
if (p == FINGERPRINT_OK) {
Serial.println("Found a print match!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else {
Serial.println("Unknown error");
return p;
}
// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
}
// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
uint8_t p = finger.getImage();
if (p != FINGERPRINT_OK) return -1;
p = finger.image2Tz();
if (p != FINGERPRINT_OK) return -1;
p = finger.fingerFastSearch();
if (p != FINGERPRINT_OK) return -1;
// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
}
Can somebody let me know if there is something wrong in my code or circuit?

ESP8266 - Setting Wifi Credentials programmatically and then checking they are valid, and then change them if they are not (without reset)

I have an NodeMCU chip that needs to connect to my home wifi and post an http request. I use the chip in WIFI_STA_AP mode as I need the chip to both accept requests via http and issue requests by http.
I do not want to hard-code my home's SSID/Password into the chip, so I have written some code that places the ESP (NodeMCU) into AP mode, receives the SSID/Pass via an http request and saves it on EEPROM.
This works great.
In the code below, onTestWifi() is called when I call http://192.168.4.1/test_wifi?wifi_ssid=mySsid&wifi_password=myPassword. The ssid and password are provided to the WiFi.begin() function. However, if I accidentally type in the wrong password and use it in WiFi.begin(), the connection will always fail until reset the chip and then insert the correct password.
What am I missing? Is it possible to change the ESP's wifi credentials programmatically, without having to reset the chip? Resetting the chip causes the client (in the case, an iPhone app) to disconnect from the chip and this breaks the entire program flow.
Here's the experimentation code I am using:
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
yield();
}
void loop() {
server.handleClient();
}```
OK, so I figured it out. Had to add the line WiFi.disconnect(true) in the onTestWifi() function. Apparently it disconnects from the network and erases the credentials. This stuff is very poorly documented and I wasted days on it.
I hope someone finds it useful.
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
WiFi.disconnect(true); // <--- Added this line
yield();
}
void loop() {
server.handleClient();
}

Arduino ESP8266 01 MQTT Raspberry pi

I want to use ESP 8266 01 and arduino uno as client in MQTT. The code For ESP8266 01 is successfully compiled and I'M getting errors in Arduino uno
The error is 'messageTemp' was not declared in this scope
Amd also I have a thought of using stm32xx in client.
If I compile for that
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]
above is the error I'm getting
1)ESP code
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
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.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
if(topic=="home/office/esp1/gpio2"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
// digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
// digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("home/office/esp1/gpio2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Code for Arduino UNO
void setup(){
Serial.begin(9600);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
String messageTemp;
}
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
void loop ()
{
if (Serial.available()){
char topic = Serial.read();
{
if (topic=="home/office/esp1/gpio2")
{
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
digitalWrite(12, HIGH);
Serial.print("On");
}
else if(messageTemp == "0")
{
digitalWrite(12, LOW);
Serial.print("Off");
}
}}}}
ESP code doesn't look the whole source code you provided. In case of Arduino UNO, if you're intending to use messageTemp as a global variable, then you need to declare it only one time outside of functions. In the above code, you declared it twice in setup() and callback(), then those are considered as local variables. Even in loop(), there's no declaration, this should create the compile error.

Arduino's serial communication with gsm board

I am trying to write a program where arduino receives text from the gsm module.But my program is able to read the first text and perform a duty,but i want it to receive multiple texts and perform individual tasks for each respective texts?Any help will be great.Thank You.
#include <SoftwareSerial.h>
SoftwareSerial gsm(2, 3);
String inString[64]; // string to hold input coming from device
String read;
int count = 0;
boolean verifyingDone = false; // flags to determine the action completed and to perform next action
boolean regist = false;
boolean registercomplete = false;
boolean location = false;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
gsm.begin(4800);
delay(100);
gsm.print("ate0\r"); // removes the echo from the device
delay(100);
gsm.print("at+cnmi=1,2,0,0,0\r"); // to receive a text
Serial.print("The Device has been Intiated");
}
void loop() {
if (gsm.available())
{
while (gsm.available())
{
read = gsm.readString();
verifyNum(); // verifying the number
/* verifyingDone=true;
if(verifyingDone){
delay(1000);
gsm.print("at+cgpsinfo\r");
delay(1000);
checkGps();
verifyingDone=false;
*/
reading1: inString[count++] = read;
Serial.print(String(read));
if (count == 64) {
break;
}
}
delay(200);
count = 0;
}
}
void clearBufferArray()
{
for (int i = 0; i < count; i++)
{
inString[i] = "";
}
}
void verifyNum() {
if (read.startsWith("\r\n+CMT: ")) { // checking the incoming text and verifying the pre-defined number
int index1 = read.indexOf('"');
int index2 = read.indexOf('"', index1 + 1);
String Number = read.substring(index1 + 2, index2);
char floatbuf[100]; // make this at least big enough for the whole string
Number.toCharArray(floatbuf, 100);
int number = atoi(floatbuf);
//Serial.println(number);
delay(1000);
if (strcmp(number, 24190) == 0)
{
Serial.println("The Sending number is " + Number);
Serial.println("This is the registered number");
regist = true;
if (regist) {
gsm.print("AT+CMGS=\"0434519166\"\r"); // Sending registeration confirmation via sms
delay(100);
gsm.print("Success this mobile number has been registered .\r");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(10000);
registercomplete = true;
if (regist == true && registercomplete == true) { //after complete registeration ,checking the gps and sending the co-ordinates
checkGps();
delay(500);
}
}
else {
gsm.print("AT+CMGSO=\"0434519166\" \,\"Someone tried to access your device\"\r"); // When not a registered number
}
}
}
}
void checkGps()
{
Serial.print("Gps Search has started");
delay(10000);//big delay to complete previous process //Not able to do this process completely------>Coz not able to re-read the string obtained from the first read..have to find an alternate to read incoming signals efficiently and re-using it
clearBufferArray();
delay(1000);
gsm.write("at+cgpsinfo\r");
delay(10000);
Serial.println();
Serial.println();
Serial.print("Locating.....Wait for a moment");
/*int spacePosition = read.indexOf(':');
if (read.charAt(spacePosition + 1) == ',' && regist==true )*/
if (read.startsWith("\r\n+CGPINFO:,,,"))
{
Serial.println("GPS signal not found.Go outside"); //
gsm.print("AT+CMGS=\"0434519166\"\r"); // Sending location as sms
delay(100);
gsm.print("GPS signal not found.Go outside ");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(1000);
regist = false;
}
else
{
Serial.println("Signal found");
gsm.print("AT+CMGS=\"0434519166\"\r"); //Confirming signal found and sending location----->location finding programs can be obtained from previouses sketches
delay(100);
gsm.print("GPS found.Location will be sent soon ");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(1000);
}
}
Thank You,Above code is justa tryout ,any help is welcome!

NodeMCU auto-join open wifi

I have searched for solution for this issue for quite a long time with no luck.
I would like NodeMCU to look for an open wifi network and connect to it. As long as the connection is available use that connection - and when the connection drops start looking for a new open network.
I live in Finland and we have free open WiFi almost on every corner. I am planning on creating something wearable/mobile that would use WiFi when available.
I am also only starting on programming, basics in C and using the Arduino IDE so no Lua language experience here.
I understand that WiFi.scanNetworks() can distinguish a secure from an unsecured SSID, but I haven't found out how I could use that to my advantage in Arduino IDE.
You can scan for networks also in STA mode.
The method you need is WiFi.encryptionType() after WiFi.scanNetworks() to determine whether a network encrypted or not.
I am sharing a sketch with you that I was working on for a similar project previously.
Sketch searches for WiFi networks, sorts them in order to RSSI, and performs connection on non-encrypted one with highest strength.
Here it is, good luck:
#include <ESP8266WiFi.h>
/* Serial Baud Rate */
#define SERIAL_BAUD 9600
/* Delay paramter for connection. */
#define WIFI_DELAY 500
/* Max SSID octets. */
#define MAX_SSID_LEN 32
/* Wait this much until device gets IP. */
#define MAX_CONNECT_TIME 30000
/* SSID that to be stored to connect. */
char ssid[MAX_SSID_LEN] = "";
/* Scan available networks and sort them in order to their signal strength. */
void scanAndSort() {
memset(ssid, 0, MAX_SSID_LEN);
int n = WiFi.scanNetworks();
Serial.println("Scan done!");
if (n == 0) {
Serial.println("No networks found!");
} else {
Serial.print(n);
Serial.println(" networks found.");
int indices[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) {
std::swap(indices[i], indices[j]);
}
}
}
for (int i = 0; i < n; ++i) {
Serial.print(WiFi.SSID(indices[i]));
Serial.print(" ");
Serial.print(WiFi.RSSI(indices[i]));
Serial.print(" ");
Serial.print(WiFi.encryptionType(indices[i]));
Serial.println();
if(WiFi.encryptionType(indices[i]) == ENC_TYPE_NONE) {
Serial.println("Found non-encrypted network. Store it and exit to connect.");
memset(ssid, 0, MAX_SSID_LEN);
strncpy(ssid, WiFi.SSID(indices[i]).c_str(), MAX_SSID_LEN);
break;
}
}
}
}
void setup() {
Serial.begin(SERIAL_BAUD);
Serial.println("Started.");
}
void loop() {
if(WiFi.status() != WL_CONNECTED) {
/* Clear previous modes. */
WiFi.softAPdisconnect();
WiFi.disconnect();
WiFi.mode(WIFI_STA);
delay(WIFI_DELAY);
/* Scan for networks to find open guy. */
scanAndSort();
delay(WIFI_DELAY);
/* Global ssid param need to be filled to connect. */
if(strlen(ssid) > 0) {
Serial.print("Going to connect for : ");
Serial.println(ssid);
/* No pass for WiFi. We are looking for non-encrypteds. */
WiFi.begin(ssid);
unsigned short try_cnt = 0;
/* Wait until WiFi connection but do not exceed MAX_CONNECT_TIME */
while (WiFi.status() != WL_CONNECTED && try_cnt < MAX_CONNECT_TIME / WIFI_DELAY) {
delay(WIFI_DELAY);
Serial.print(".");
try_cnt++;
}
if(WiFi.status() == WL_CONNECTED) {
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("Cannot established connection on given time.");
}
} else {
Serial.println("No non-encrypted WiFi found.");
}
}
}

Resources