 
     wifi.println("AT+RST");
     wifi.println("AT+CWMODE=1");
-    delay(500); //delay after mode change
+    delay(1000); //delay after mode change
     wifi.println("AT+CWJAP_CUR=\"" + SSID + "\",\"" + PASS + "\"");
-    if (wifi.find("OK")) {
+    delay(1000);
+    if (!wifi.find("OK")) {
         Serial.println("error connecting AP");
         return false;
     }

}

boolean connectWiFi() {
    wifi.begin(9600);

    Serial.print("Connecting... ");

    wifi.println("AT");
    if (!wifi.find("OK")) {
        Serial.println("error connecting module");
        return false;

    pinMode(sensor, INPUT);
    pinMode(light, OUTPUT);

    Serial.begin(115200);
    while(!connectWiFi()) {
      Serial.println("Retrying connect to network");
    }
