Using millis to control the amount of time a continuous

I am using the code by kokopapa to have the servo be able to be controlled by alexa. And I need the servo to stop after a certain amount of time. I have read around online that using millis() is the best option for this kind of work. I have wrote the code below but whenever I run it, it doesn't work. Please help.

// Beware LED is inverse, GPIO2=0 to light, and note 'Cloud Inside' boards have led on GPIO1
// Based heavily on Kakopappa's Wemo emulation code. Servo variation by Phil_G.

unsigned long startTime, currentTime;
unsigned long runTime = 5000;

unsigned int localPort = 1900; // local port to listen on
int pwmpulse=1500;
WiFiUDP UDP;

void setup() {
startTime=millis();
Serial.begin(115200);
delay(1000);
// Setup Servo
pinMode(servoPin, OUTPUT);

prepareIds();

// Initialise wifi connection
wifiConnected = connectWifi();

// only proceed if wifi connection successful
if(wifiConnected){
Serial.print("Wifi connected ok ");
udpConnected = connectUDP();

if (udpConnected){
// initialise pins if needed
Serial.print("udp connected ");
startHttpServer();
}
}
}

void loop() {
currentTime = millis();

HTTP.handleClient();
delay(1);

// if there's data available, read a packet
// check if the WiFi and UDP connections were successful
if(wifiConnected){
if(udpConnected){
// if there’s data available, read a packet
int packetSize = UDP.parsePacket();

if(packetSize) {
Serial.println("");
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = UDP.remoteIP();

for (int i =0; i < 4; i++) {
Serial.print(remote*, DEC);*

  • if (i < 3) {*

  • Serial.print(".");*

  • }*

  • }*

  • Serial.print(", port ");*

  • Serial.println(UDP.remotePort());*

  • int len = UDP.read(packetBuffer, 255);*

  • if (len > 0) {*

  • packetBuffer[len] = 0;*

  • }*

  • String request = packetBuffer;*

  • //Serial.println("Request:");*

  • //Serial.println(request);*

  • if(request.indexOf('M-SEARCH') > 0) {*
    _ if(request.indexOf("urn:Belkin:device:**") > 0) {_

  • Serial.println("Responding to search request ...");*

  • respondToSearch();*

  • }*

  • }*

  • }*

  • delay(18);*

  • digitalWrite(servoPin,1);*

  • delayMicroseconds(pwmpulse);*

  • digitalWrite(servoPin,0);*

  • }*
    } else {

  • // Turn on/off to indicate cannot connect .. *
    }
    }
    void prepareIds() {
    uint32_t chipId = ESP.getChipId();
    char uuid[64];
    sprintf_P(uuid, PSTR("38323636-4558-4dda-9188-cda0e6%02x%02x%02x"),

  • (uint16_t) ((chipId >> 16) & 0xff),*

  • (uint16_t) ((chipId >> 8) & 0xff),*

  • (uint16_t) chipId & 0xff);*
    serial = String(uuid);
    persistent_uuid = "Socket-1_0-" + serial;
    }
    void respondToSearch() {

  • Serial.println("");*

  • Serial.print("Sending response to ");*

  • Serial.println(UDP.remoteIP());*

  • Serial.print("Port : ");*

  • Serial.println(UDP.remotePort());*

  • IPAddress localIP = WiFi.localIP();*

  • char s[16];*

  • sprintf(s, "%d.%d.%d.%d", localIP[0], localIP[1], localIP[2], localIP[3]);*

  • String response =*

  • "HTTP/1.1 200 OK\r\n"*

  • "CACHE-CONTROL: max-age=86400\r\n"*

  • "DATE: Fri, 15 Apr 2016 04:56:29 GMT\r\n"*

  • "EXT:\r\n"*

  • "LOCATION: http://" + String(s) + ":80/setup.xml\r\n"*

  • "OPT: "http://schemas.upnp.org/upnp/1/0/\"; ns=01\r\n"*

  • "01-NLS: b9200ebb-736d-4b93-bf03-835149d13983\r\n"*

  • "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n"*
    _ "ST: urn:Belkin:device:\r\n"_
    "USN: uuid:" + persistent_uuid + "::urn:Belkin:device:
    \r\n"

  • "X-User-Agent: redsonic\r\n\r\n";*

  • UDP.beginPacket(UDP.remoteIP(), UDP.remotePort());*

  • UDP.write(response.c_str());*

  • UDP.endPacket(); *

  • Serial.println("Response sent !");*
    }
    void startHttpServer() {

  • HTTP.on("/index.html", HTTP_GET, {*

  • Serial.println("Got Request index.html ...\n");*

  • HTTP.send(200, "text/plain", "Hello World!");*

  • });*

  • HTTP.on("/upnp/control/basicevent1", HTTP_POST, {*

  • Serial.println("########## Responding to /upnp/control/basicevent1 ... ##########"); *

  • //for (int x=0; x <= HTTP.args(); x++) {*

  • // Serial.println(HTTP.arg(x));*

  • //}*

  • String request = HTTP.arg(0); *

  • Serial.print("request:");*

  • Serial.println(request);*

  • if(request.indexOf("1") > 0) {*

  • Serial.println("Got Turn on request");*

  • turnOnServo();*

  • }*

  • if(request.indexOf("0") > 0) {*

  • Serial.println("Got Turn off request");*

  • turnOffServo();*

  • }*

  • HTTP.send(200, "text/plain", "");*

  • });*

  • HTTP.on("/eventservice.xml", HTTP_GET, {*

  • Serial.println(" ########## Responding to eventservice.xml ... ########\n");*

  • String eventservice_xml = "<?scpd xmlns=\"urn:Belkin:service-1-0\"?>"*

  • ""*

  • ""*

  • "SetBinaryState"*

  • ""*

  • ""*

  • ""*

  • "BinaryState"*

  • "BinaryState"*

  • "in"*

  • ""*

  • ""*

  • ""*

  • "<stateVariable sendEvents="yes">"*

  • "BinaryState"*

  • "Boolean"*

  • "0"*

  • ""*

  • "<stateVariable sendEvents="yes">"*

  • "level"*

  • "string"*

  • "0"*

  • ""*

  • ""*

  • ""*

  • "\r\n"*

  • "\r\n";*

  • HTTP.send(200, "text/plain", eventservice_xml.c_str());*

  • });*

  • HTTP.on("/setup.xml", HTTP_GET, {*

  • Serial.println(" ########## Responding to setup.xml ... ########\n");*

  • IPAddress localIP = WiFi.localIP();*

  • char s[16];*

  • sprintf(s, "%d.%d.%d.%d", localIP[0], localIP[1], localIP[2], localIP[3]);*

  • String setup_xml = "<?xml version=\"1.0\"?>"*

  • ""*

  • ""*

  • "urn:Belkin:device:controllee:1"*

  • ""+ device_name +""*

  • "Belkin International Inc."*

  • "Emulated Socket"*

  • "3.1415"*

  • "uuid:"+ persistent_uuid +""*

  • "221517K0101769"*

  • "0"*

  • ""*

  • ""*

  • "urn:Belkin:service:basicevent:1"*

  • "urn:Belkin:serviceId:basicevent1"*

  • "/upnp/control/basicevent1"*

  • "/upnp/event/basicevent1"*

  • "/eventservice.xml"*

  • ""*

  • ""*

  • ""*

  • "\r\n"*

  • "\r\n";*

  • HTTP.send(200, "text/xml", setup_xml.c_str());*

  • Serial.print("Sending :");*

  • Serial.println(setup_xml);*

  • });*

  • HTTP.begin(); *

  • Serial.println("HTTP Server started ..");*
    }

// connect to wifi – returns true if successful or false if not
boolean connectWifi(){
boolean state = true;
int i = 0;
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("Connecting to WiFi");
// Wait for connection
Serial.print("Connecting ...");
while (WiFi.status() != WL_CONNECTED) {

  • delay(500);*
  • Serial.print(".");*
  • if (i > 50){*
  • state = false;*
  • break;*
  • }*
  • i++;*
    }
    if (state){
  • Serial.println("");*
  • Serial.print("Connected to ");*
  • Serial.println(ssid);*
  • Serial.print("IP address: ");*
  • Serial.println(WiFi.localIP());*
    }
    else {
  • Serial.println("");*
  • Serial.println("Connection failed.");*
    }
    return state;
    }
    boolean connectUDP(){
    boolean state = false;
    Serial.println("");
    Serial.println("Connecting to UDP");
    if(UDP.beginMulticast(WiFi.localIP(), ipMulti, portMulti)) {
  • Serial.println("Connection successful");*
  • state = true;*
    }
    else{
  • Serial.println("Connection failed");*
    }
    return state;
    }
    void turnOnServo() {
    while (currentTime-startTime>=runTime){ //It keep skipping over this while loop and execute the
  • pwmpulse = 1365.*
  • currentTime=millis();*
  • pwmpulse=1000;*
  • startTime=currentTime;*
    }
    pwmpulse=1365;
    }
    void turnOffServo() {
    pwmpulse=2000;
    }

I have wrote the code below but whenever I run it, it doesn't work. Please help.

How can we? The code you posted improperly, because you couldn't be bothered to read the stickies at the top of the forum, does something. You haven't told us what it actually does.

You expect the code to do something. You haven't told us what you expect it to do.

If you expect turnOnServo() to start the servo moving, and for the servo to stop after some period of time, then your expectations are completely wrong.

turnOnServo() should do exactly what it's name implies, and NOTHING more. Except, of course, recording WHEN it turned the servo on.

loop() should determine what time it is, and, if the servo is on, how long it has been on. If it is on, and has been on long enough, loop() should turn it off, and clear the servo on time variable, so loop() knows that the servo is not on.

To make it easy for people to help you please modify your post and use the code button </>

so your code looks like this

and is easy to copy to a text editor. See How to use the Forum

Your code is much too long for me to study quickly without copying to a text editor.

Also please use the AutoFormat tool to indent your code for easier reading.

...R

unsigned long ServoStartTime = 0;
const unsigned long ServoRunTime = 1234; // milliseconds
const int ServoRunPulseWidth = 1750;
const int ServoStopPulseWidth = 1500;  // The pulse width where the motor stops
const byte ServoPin = 5;


#include <Servo.h>


Servo servo;


void setup()
{
  servo.attach(ServoPin);


  // When you want the motor sot start running:
  servo.writeMicroseconds(ServoRunPulseWidth);
  ServoStartTime = millis();
}


void loop()
{
  if (ServoStartTime != 0 && millis() - ServoStartTime >= ServoRunTime)
  {
    // Timer is running AND timer has now expired
    servo.writeMicroseconds(ServoStopPulseWidth);
    ServoStartTime = 0;  // Timer is not running
  }
}

PaulS:
How can we? The code you posted improperly, because you couldn't be bothered to read the stickies at the top of the forum, does something. You haven't told us what it actually does.

You expect the code to do something. You haven't told us what you expect it to do.

If you expect turnOnServo() to start the servo moving, and for the servo to stop after some period of time, then your expectations are completely wrong.

turnOnServo() should do exactly what it's name implies, and NOTHING more. Except, of course, recording WHEN it turned the servo on.

loop() should determine what time it is, and, if the servo is on, how long it has been on. If it is on, and has been on long enough, loop() should turn it off, and clear the servo on time variable, so loop() knows that the servo is not on.

What this code is suppose to do is closing the blinds and opening it, which is why i tried to implement the millis in the "turnOnServo" function. As for what the code i posted actually does, it execute the turnOnServo function when i tell Alexa to "turn on Servo" and execute turnOffServo when i tell Alexa to "turn off Servo". But whenever i tell Alexa to turnOnServo it execute the TurnOnServo funtion but skipped over the while statement that i wrote in the function.