Hi guys, i need some help on my program
-Im using a ultrasonic sensor sr04 to detect the movement
-If there is no movement ledState=HIGH, if there is a movment ledState=LOW
-If ledState=HIGH for 5 sec it will trigger modem to turn OFF
-If ledState=LOW for 5 sec it will restart the board
I've run the ultrasonic & wifi connecting code separately, its works well
but after combined the code with 'millis delay' to control the modem sleep time its seems the modem not going to sleep
can anyone enlighten me?
#include <ESP8266WiFi.h>
/*Ultrasonic Sensor*/
// defines Pin
int echoPin = D1;
int trigPin = D2;
int ledPin = D3;
int ledState = HIGH;
// defines Ultrasonic variables
long duration;
int distance;
// define Ultrasonic range
int maximumRange = 10; // Maximum range needed
int minimumRange = 0; // Minimum range needed
/*Network*/
// WiFi Connection
const char* ssid = "xxxxx";
const char* password = "xx";
WiFiServer server(80);
// Millis Delay
unsigned long start;
unsigned long now;
const int WifiOff = 5000; // WifiOff...8second
void setup() {
Serial.begin(115200);
delay(10);
//Ultrasonic Sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//Unit Varible
ledState = HIGH;
//Unit LED output
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
IPAddress ip(xx,x,x,xx);
IPAddress gateway(xx,x,x,x);
IPAddress subnet(xxx,xxx,xxx,x);
WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop()
{
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
Serial.println("-1");
ledState = HIGH;
}
if(ledState==HIGH)
{
Serial.print("NO movement!!");
start = millis();
}
now=millis();
if(now - start > WifiOff)
{
WiFi.disconnect();
WiFi.forceSleepBegin();
delay(1);
Serial.print("WifiOff");
}
else {
/* Send the distance to the computer using Se
* rial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
ledState = LOW;
ESP.restart();
}
// Update the LED based on ledState
digitalWrite(ledPin, ledState);
delay(50);
}