Arduino Wifi Setup
A IoT device programmed with Arduino need connect to WiFi at start of device to use internet for data transfer etc. First of all we need to include header file “WiFiClient” to our sketch.
#include <WiFiClient.h>
With code below we will let user enter WiFi credentials over serial communication. we should add this code to our setup() part of our Arduino sketch.
Serial.write("Please enter name of your wifi network\n");
while(Serial.available() == 0){};
String Uid=Serial.readStringUntil('\n');
Serial.write("Please enter password of your wifi network\n");
while(Serial.available() == 0){};
String pass= Serial.readStringUntil('\n');
If you want give user a tool to setup WiFi over serial you can download a free serial communication tool “Vengito Serial Tool”. With this tool user can connect IoT device easily and enter WiFi credentials.
Download "Vengito Serial Tool"
After user entered credentials device should try connecting to internet. Code below have 3 parts and also should be in setup() part of our sketch. First part disconnects from any WiFi network if it is connected already. Second part starts connection with Wifi.begin function. And the last part waits connecting and gives IP address of device over serial port if device connected WiFi successfully.
WiFi.disconnect();
delay(1000);
WiFi.begin(Uid, pass); //begin WiFi connection
Serial.println("Started");
unsigned long startedWaiting = millis();
// Wait for connection
while (WiFi.status() != WL_CONNECTED && millis() - startedWaiting <= 25000)
{
delay(500);
Serial.print("*");
}
if(WiFi.status() != WL_CONNECTED)
{
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
You can try this code with ESP8266 or any other chip which supports Arduino.
Comments
Post a Comment