#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Wire.h>
const char* ssid = "A1601";
const char* password = "top3264737123456789";
WiFiUDP Udp;
unsigned int localUdpPort = 8080; // local port to listen on
//-------------------------------
char incomingPacket[255]; // buffer for incoming packets
boolean stringComplete = false;
char pass[] = {'s','t','c','1','7'};
boolean datachk[100];
boolean passcheck = false;
//------------------------------------------
int ledPin1=D0; // กำหนดขา Output LED
//-----------------------------------------
void setup()
{
Serial.begin(115200);
Serial.println();
pinMode(ledPin1,OUTPUT); // OUTPUT LED 1
digitalWrite(ledPin1,LOW); // OFF LED
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
Udp.begin(localUdpPort);
Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
}
//------------------------------------
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
// receive incoming UDP packets
Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(incomingPacket, 255);
if (len > 0)
{
incomingPacket[len] = 0;
}
Serial.printf("UDP packet contents: %s\n", incomingPacket);
stringComplete = true;
}
//----------------------------------------------------------------
// if arduino receive a string termination character like \n stringComplete will set to true
if (stringComplete)
{
delay(100);
//----------- เช็คความถูกต้องของ Password รอบละ 1 ตัว ------------
for(int i=0; i<sizeof(pass) ;i++)
{
if(incomingPacket[i]==pass[i]) // ถ้าเช็ค Password ถูกต้อง
{
Serial.print(i);
Serial.println("true");
datachk[i] = true;
}
else // ถ้าเช็ค Password ไม่ถูกต้อง
{
Serial.println("FALSE");
datachk[i] = false;
}
}
//-------- ตรวจเช็คจำนวน Password ว่าถูกต้องกี่ตัว --------
for(int i =0;i<sizeof(pass);i++)
{
if(datachk[i]==true) // Password ถูกต้อง
{
passcheck = true;
Serial.println("1: true");
}
else // Password ไม่ถูกต้อง
{
passcheck = false;
Serial.println("0: FALSE");
}
}
//---------------- ปฏิบัติตามเงื่อนไข ----------------------
if(passcheck==true) // ถ้า Password ถูกต้องครบทุกตัว
{
Serial.println("PASSWORD TRUE");
digitalWrite(ledPin1,HIGH); // ON LED
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write("TRUE");
Udp.endPacket();
}
else // ถ้า Password ไม่ถูกต้องครบทุกตัว
{
Serial.println("PASSWORD FALSE");
digitalWrite(ledPin1,LOW); // OFF LED
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write("FALSE");
Udp.endPacket();
}
stringComplete = false;
}
}
ใส่ if เช็คเพิ่มตรงนี้ครับ
if(incomingPacket[i]==pass[i]) // ถ้าเช็ค Password ถูกต้อง
{
Serial.print(i);
Serial.println("true");
datachk[i] = true;
}