Switch from Wifi Access Point mode to station mode using esp32 - reactjs

I am making my esp32 an access point and once the client connects with access point, it shares it's Home wifi credentials (ssid and password). Then I use this ssid and password to connect the esp32 with Home wifi.
But It is not connecting with Home wifi. I try to disconnect/stop access point but got no luck.
Arduino Code:
#include <WiFi.h>
#include "aWOT.h"
#include "StaticFiles.h"
#define LED_BUILTIN 2
const char* ssid = "SSID";
const char* password = "Password";
WiFiServer server(80);
Application app;
String CompleteSSID="";
String CompletePassword="";
//Read SSID from web
void readSSID(Request &req, Response &res) {
res.print(CompleteSSID);
}
void updateSSID(Request &req, Response &res) {
while(req.available())
{
char currentword=req.read();
CompleteSSID+=currentword;
}
Serial.println(CompleteSSID);
//digitalWrite(LED_BUILTIN, '1');
return readSSID(req, res);
}
void readPassword(Request &req, Response &res) {
res.print(CompletePassword);
}
void updatePassword(Request &req, Response &res) {
while(req.available())
{
char currentword=req.read();
CompletePassword+=currentword;
}
Serial.println(CompletePassword);
//digitalWrite(LED_BUILTIN, '1');
ConnectToHomeWiFi();
return readPassword(req, res);
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.println(IP);
app.get("/ssid", &readSSID);
app.put("/ssid", &updateSSID);
app.get("/password", &readPassword);
app.put("/password", &updatePassword);
app.route(staticFiles());
server.begin();
}
void ConnectToHomeWiFi()
{
char* ssid_n;
char* pass_n;
CompleteSSID.toCharArray(ssid_n, CompleteSSID.length());
CompletePassword.toCharArray(pass_n, CompletePassword.length());
//WiFi.softAPdisconnect();
WiFi.disconnect(true);
WiFi.persistent(false);
//WiFi.setAutoConnect(false);
//WiFi.mode(WIFI_OFF);
//WiFi.setOutputPower(0);
//WiFi.reconnect();
WiFi.mode(WIFI_STA);
delay(100);
WiFi.begin(ssid_n, pass_n);
Serial.print("Connecting to ");
Serial.println(CompleteSSID);
uint8_t i = 0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(500);
if ((++i % 16) == 0)
{
Serial.println(F(" still trying to connect"));
}
}
Serial.print(F("Connected. My IP address is: "));
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (client.connected()) {
app.process(&client);
}
}
What am I doing wrong in disconnecting SoftAp or connecting with home wifi?
Thanks!

Here is the solution of this issue:
void setup(){
.....
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.println(IP);
....
server.begin();
}
void ConnectToHomeWiFi()
{
....
WiFi.begin(ssid_n,pass_n);
....
}
There is no need of disconnecting Access point, changing the mode and then using WiFi.begin. By using only WiFi.begin, we can connect to any WiFi.

Related

how to get input value from ultrasonic sensor on copper web application (coap protocol)

i can't use 'GET' in copper.I know that ultrasonic sensors can't be set like lights (binary data). but I just want to get a description of the if parameter I've made
if (jarak < 50) {
Serial.println ("jarak Aman ");
}
else {
Serial.println ("harus diisi");
this is the full code
#include <ESP8266WiFi.h>
#include <coap_server.h>
#include <Ultrasonic.h>
#define triggerPin D8
#define echoPin D7
char * duration, jarak;
coapServer coap;
//WiFi connection info
const char* ssid = "ZTE-d17d4e";
const char* password = "amatapit";
bool LEDSTATE;
//Setup
void setup() {
yield();
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
//serial begin
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println(" ");
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
//delay(500);
yield();
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.println(WiFi.localIP());
// LED State
pinMode(16, OUTPUT);
digitalWrite(16, HIGH);
LEDSTATE = true;
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
//LEDSTATE = true;
// add server url endpoints.
// can add multiple endpoint urls.
coap.server(callback_light, "light");
coap.server(callback_sensor, "sensor");
// start coap server/client
coap.start();
// coap.start(5683);
}
void loop() {
coap.loop();
delay(1000);
long duration, jarak;
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
//inches = microsecondsToInches(duration);
// cm = microsecondsToCentimeters(duration);
jarak = duration/29/2;
Serial.print("Jarak :");
Serial.println(jarak);
Serial.print(" cm");
Serial.println("");
if (jarak < 50) {
Serial.println ("jarak Aman ");
}
else {
Serial.println ("harus diisi");
}
delay(500);
}
// CoAP server endpoint URL
void callback_light(coapPacket *packet, IPAddress ip, int port,int obs) {
Serial.println("light");
// send response
char p[packet->payloadlen + 1];
memcpy(p, packet->payload, packet->payloadlen);
p[packet->payloadlen] = NULL;
Serial.println(p);
String message(p);
if (message.equals("0"))
{
digitalWrite(16,LOW);
Serial.println("Lampu Mati");
}
else if (message.equals("1"))
{
digitalWrite(16,HIGH);
Serial.println("Lampu Menyala");
}
char *light = (digitalRead(16) > 0)? ((char *) "Lampu Menyala:") :((char *) "Lampu Mati");
//coap.sendResponse(packet, ip, port, light);
if(obs==1)
coap.sendResponse(light);
else
coap.sendResponse(ip,port,light);
}
void callback_sensor(coapPacket *packet, IPAddress ip, int port,int obs) {
Serial.println("sensor");
// send response
char p[packet->payloadlen + 1];
memcpy(p, packet->payload, packet->payloadlen);
p[packet->payloadlen] = NULL;
Serial.println(p);
String message(p);
if (message.equals("1"))
{
// digitalWrite(16,LOW);
Serial.println(jarak);
}
else if (message.equals("2"))
{
// digitalWrite(16,HIGH);
Serial.println(jarak);
}
char *sensor = ((jarak) > 0)? ((char *) "Nyala nih") :((char *) "Mati");
//coap.sendResponse(packet, ip, port, sensor);
if(obs==1)
coap.sendResponse(sensor);
else
coap.sendResponse(ip,port,sensor);
}#include <ESP8266WiFi.h>
#include <coap_server.h>
#include <Ultrasonic.h>
#define triggerPin D8
#define echoPin D7
char * duration, jarak;
coapServer coap;
//WiFi connection info
const char* ssid = "ZTE-d17d4e";
const char* password = "amatapit";
bool LEDSTATE;
//Setup
void setup() {
yield();
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
//serial begin
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println(" ");
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
//delay(500);
yield();
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.println(WiFi.localIP());
// LED State
pinMode(16, OUTPUT);
digitalWrite(16, HIGH);
LEDSTATE = true;
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
//LEDSTATE = true;
// add server url endpoints.
// can add multiple endpoint urls.
coap.server(callback_light, "light");
coap.server(callback_sensor, "sensor");
// start coap server/client
coap.start();
// coap.start(5683);
}
void loop() {
coap.loop();
delay(1000);
long duration, jarak;
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
//inches = microsecondsToInches(duration);
// cm = microsecondsToCentimeters(duration);
jarak = duration/29/2;
Serial.print("Jarak :");
Serial.println(jarak);
Serial.print(" cm");
Serial.println("");
if (jarak < 50) {
Serial.println ("jarak Aman ");
}
else {
Serial.println ("harus diisi");
}
delay(500);
}
// CoAP server endpoint URL
void callback_light(coapPacket *packet, IPAddress ip, int port,int obs) {
Serial.println("light");
// send response
char p[packet->payloadlen + 1];
memcpy(p, packet->payload, packet->payloadlen);
p[packet->payloadlen] = NULL;
Serial.println(p);
String message(p);
if (message.equals("0"))
{
digitalWrite(16,LOW);
Serial.println("Lampu Mati");
}
else if (message.equals("1"))
{
digitalWrite(16,HIGH);
Serial.println("Lampu Menyala");
}
char *light = (digitalRead(16) > 0)? ((char *) "Lampu Menyala:") :((char *) "Lampu Mati");
//coap.sendResponse(packet, ip, port, light);
if(obs==1)
coap.sendResponse(light);
else
coap.sendResponse(ip,port,light);
}
void callback_sensor(coapPacket *packet, IPAddress ip, int port,int obs) {
Serial.println("sensor");
// send response
char p[packet->payloadlen + 1];
memcpy(p, packet->payload, packet->payloadlen);
p[packet->payloadlen] = NULL;
Serial.println(p);
String message(p);
if (message.equals("1"))
{
// digitalWrite(16,LOW);
Serial.println(jarak);
}
else if (message.equals("2"))
{
// digitalWrite(16,HIGH);
Serial.println(jarak);
}
char *sensor = ((jarak) > 0)? ((char *) "Nyala nih") :((char *) "Mati");
//coap.sendResponse(packet, ip, port, sensor);
if(obs==1)
coap.sendResponse(sensor);
else
coap.sendResponse(ip,port,sensor);
}
To analyse the issue, you may also try other clients, e.g. libcoap or Californium. If that still results in trouble, a IP capture helps to understand the case.
Or, is your question more about your server-side code than about coap? Then some logs from your server may help to understand, how it works and to find the issue there.

Saving Custum Paramter with WifiManager & Arduinojson 6

I'm trying to save an additional custom parameter to wifimanager which is the mqtt server address but all codes available in the library and all over the internet are for Arduinojson 5, I tried upgrading to Arduinojson 6 to the best of my ability. The code runs with no issues, however, when I restart the esp, it is gone. For somereason, it is not saved.
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#define TRIGGER_PIN 16
char mqtt_server[40];
bool shouldSaveConfig = false;
void saveConfigCallback () { Serial.println("Should save config"); shouldSaveConfig = true; }
WiFiManager wifiManager;
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
void setup() {
Serial.begin(115200);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT);
//clean FS, for testing
//SPIFFS.format();
if (SPIFFS.begin()) {
Serial.println("** Mounting file system **");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("** Reading config file **");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, buf.get());
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
strcpy(mqtt_server, doc["mqtt_server"]); //get the mqtt_server <== you need one of these for each param
} else {
Serial.println("** Failed to load json config **");
}
configFile.close();
Serial.println("** Closed file **");
}
}
else {
Serial.println("** Failed to mount FS **");
}
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_mqtt_server);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
resetbtn();
}
Serial.println("connected...yeey :)");
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonDocument doc(1024);
doc["mqtt_server"] = mqtt_server;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
serializeJson(doc, Serial);
serializeJson(doc, configFile);
configFile.close();
//end save
}
}
void loop() {
resetbtn();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
resetbtn();
}
Serial.println("Connected");
wifiManager.process();
saveParamsCallback();
delay(3000);
}
void resetbtn() { if ( digitalRead(TRIGGER_PIN) == HIGH ) { wifiManager.startConfigPortal("Horray"); Serial.println("connected...yeey :)"); } }
void saveParamsCallback () {
Serial.println("Get Params:");
Serial.print(custom_mqtt_server.getID());
Serial.print(" : ");
Serial.println(custom_mqtt_server.getValue());
}
for same purpose instead of using: serializeJson(doc, configFile);
i'm using this function and for me work pretty well
// for writing
bool writeFile(const char * path, const char * message, unsigned int len){
File file = SPIFFS.open(path, FILE_WRITE);
if(!file){
return false;
}
if(!file.write((const uint8_t *)message, len)){
return false;
}
return true;
}
for reading i'm using this function
// for reading
int readFile(const char * path, char ** text){
// retval int - number of characters in the file
// in case of empty file 0
// in case of directory or not found -1
File file = SPIFFS.open(path);
if(!file || file.isDirectory()){
return -1;
}
int file_lenght = file.size();
*text = (char*) malloc(file_lenght*sizeof(char));
for(int i = 0; i < file_lenght; i++){
(*text)[i] = file.read();
}
return file_lenght;
}
you can use this function in this way:
#define WIFI_credential_filename "/config.json"
char * wifi_credentials;
int file_len = readFile(WIFI_credential_filename, &wifi_credentials);
// at this point "wifi_credentials" is filled with the content of
"/config.json" file
this is my implementation, surely it can be improved but I have tested it and it works

ESP32 HTTP.GET() return -1 and -11

I am working with ESP32, everything is working fine but when I want to make POST or even GET request I get -1 status or sometimes 11.
I tried things like :
on the other server - http/https - GET/POST- didnt work out
I'm crashed here :(
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif
#include <Wire.h>
// Replace with your network credentials
const char* ssid = "XXXXX";
const char* password = "XXXXX";
void setup() {
Serial.begin(115200);
delay(4000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
}
void loop() {
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin("http://jsonplaceholder.typicode.com/comments?id=10");
//Specify the URL
int httpCode = http.GET(); //Make the request
if (httpCode > 0) { //Check for the returning code
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(10000);
}

IBM Watson IoT - Unable to get response from topic with parameters using ESP8266

From several days I searched for this problem:
I want to do a connected device (IoT) using Watson IoT Platform and ESP32 (or similar). This device have some relays on board.
On Watson dashboard I created the device type, the physical/logical interface, I connected the ESP with the platform.
I created a custom action on the dashboard that has a param to identify the relay that I want to switch (switch2) and also a simple custom action (switch) without param.
The problem is that if I generate the action without the param (switch) I see the callback print, if I generate the action with a param (switch2) nothing happens.
I tried also to use the built-in Watson action "firmware update/download", if I use firmware download (that want some params such as uri, version, etc.) nothing happens, if I use firmware update (that don't want params), I see the callback of subscription.
Here you can see the code arduino like for the ESP
// --------------- HEADERS -------------------
#include <Arduino_JSON.h>
#include <EEPROM.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <PubSubClient.h> //https://github.com/knolleary/pubsubclient/releases/tag/v2.3
WebServer server(80);
char wifi_ssid[100] = "xxxxxx";
char wifi_psw[200] = "xxxxxxx";
// ----- Watson IBM parameters
#define ORG "xxxx"
#define DEVICE_TYPE "Relay"
#define DEVICE_ID "xxxx"
#define TOKEN "xxxxxxxxxxxxxxxx"
char ibmServer[] = ORG ".messaging.internetofthings.ibmcloud.com";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
const char switchTopic[] = "iotdm-1/mgmt/custom/switch-actions-v1/switch2";
const char testTopic[] = "iotdm-1/mgmt/custom/switch-actions-v1/switch"; //"iot-2/cmd/+/fmt/+";
const char observeTopic[] = "iotdm-1/observe";
const char publishTopic[] = "iot-2/evt/status/fmt/json";
const char responseTopic[] = "iotdm-1/response";
const char deviceResponseTopic[] = "iotdevice-1/response";
const char manageTopic[] = "iotdevice-1/mgmt/manage";
const char updateTopic[] = "iotdm-1/mgmt/initiate/firmware/update";
void callback(char* topic, byte* payload, unsigned int payloadLength);
WiFiClient wifiClient;
PubSubClient client(ibmServer, 1883, callback, wifiClient);
bool outputEnable = false;
bool oldOutputEnable = false;
void setup() {
// put your setup code here, to run once:
//Init la porta seriale ed aspetta che si avii
Serial.begin(115200);
while(!Serial) {
delay(1);
}
setupWiFi();
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.loop()) {
mqttConnect();
initManagedDevice();
}
delay(100);
}
// WiFi Settings
void setupWiFi() {
bool state = false;
Serial.println("---- Setup WiFi ----");
Serial.println(wifi_ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_psw);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
mqttConnect();
initManagedDevice();
publishStatus();
Serial.println("");
Serial.print("Connected to ");
Serial.println(wifi_ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
// IBM IoT
void mqttConnect() {
if (!!!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(ibmServer);
while (!!!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe("iotdm-1/response")) {
Serial.println("subscribe to responses OK");
} else {
Serial.println("subscribe to responses FAILED");
}
if (client.subscribe("iotdm-1/device/update")) {
Serial.println("subscribe to update OK");
} else {
Serial.println("subscribe to update FAILED");
}
if (client.subscribe(observeTopic)) {
Serial.println("subscribe to observe OK");
} else {
Serial.println("subscribe to observe FAILED");
}
if (client.subscribe(switchTopic)) {
Serial.println("subscribe to switch OK");
} else {
Serial.println("subscribe to switch FAILED");
}
if (client.subscribe(testTopic)) {
Serial.println("subscribe to Test OK");
} else {
Serial.println("subscribe to Test FAILED");
}
JSONVar root;
JSONVar d;
JSONVar supports;
supports["deviceActions"] = true;
supports["firmwareActions"] = true;
supports["switch-actions-v1"] = true;
d["supports"] = supports;
root["d"] = d;
char buff[300] = "";
JSON.stringify(root).toCharArray(buff, 300);
Serial.println("publishing device metadata:"); Serial.println(buff);
if (client.publish(manageTopic, buff)) {
Serial.println("device Publish ok");
} else {
Serial.print("device Publish failed:");
}
}
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
if (strcmp (responseTopic, topic) == 0) {
return; // just print of response for now
}
if (strcmp (updateTopic, topic) == 0) {
handleUpdate(payload);
}
if (strcmp(switchTopic, topic) == 0) {
handleRemoteSwitch(payload);
}
if(strcmp(observeTopic, topic) == 0) {
handleObserve(payload);
}
}
void sendSuccessResponse(const char* reqId) {
JSONVar payload;
payload["rc"] = 200;
payload["reqId"] = reqId;
char buff[300] = "";
JSON.stringify(payload).toCharArray(buff, 300);
if (client.publish(deviceResponseTopic, buff)) {
Serial.println("Success sended");
} else {
Serial.print("Success failed:");
}
}
void publishStatus() {
String payload = "{\"relayStatus\":";
payload += outputEnable;
payload += "}";
Serial.print("Sending payload: "); Serial.println(payload);
if (client.publish(publishTopic, (char*) payload.c_str())) {
Serial.println("Publish OK");
} else {
Serial.println("Publish FAILED");
}
}
void handleUpdate(byte* payload) {
Serial.println("handle Update");
}
void handleObserve(byte* payload) {
JSONVar request = JSON.parse((char*)payload);
JSONVar d = request["d"];
JSONVar fields = d["fields"];
const char* field = fields[0]["field"];
if(strcmp(field, "mgmt.firmware") == 0) {
Serial.println("Upadete the firmware");
sendSuccessResponse(request["reqId"]);
} else {
Serial.println("Unmanaged observe");
Serial.println(request);
}
}
void handleRemoteSwitch(byte* payload) {
Serial.println("handle remote switching");
//invertedSwitch = !invertedSwitch;
outputEnable = !outputEnable;
JSONVar request = JSON.parse((char*)payload);
const char* id = request["reqId"];
sendSuccessResponse(id);
}
Thanks to everyone that wants to try to help me.
After several days I solved the issue, I post here de response for someone with the same problem:
The problem is the PubSubClient library, that accept only 128 bytes response message (including header). The Watson IBM produce longer response message than 128 bytes.
To change the buffer size for the response message, you need to modify the PubSubClient.h file at line
#define MQTT_MAX_PACKET_SIZE 128
And change the 128 byte with bigger number (eg. 1024).

Validating User name and password

I am trying to implement user name and password from web Server application with Arduino board. Here in below code i can get username and password from user. Now question is how to compare result comparison. if User enter name and password it has to check and gives back error report.
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,128);
EthernetServer server(80);
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
if (c == '\n' && currentLineIsBlank) {
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<body>");
client.println("</form>");
client.println("USER NAME:<input type='text' name='firstname'><br>");
client.println("PASSWORD:<input type='password' name='pwd'><br>");
client.println("<input type='submit'>");
client.println("</form>");
client.println("<body>");
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
Have a look at this page for a password protected Arduino WebServer, I use this tip

Resources