Edwarddv

Untitled

Jul 12th, 2015
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. float deltaTime = 0;
  2. unsigned long previousMillis = 0;
  3.  
  4. float timerA = 0;
  5. float sendDataTimer = 0;
  6. bool awaitingResponse = false;
  7.  
  8. loop()
  9. {
  10.     //First we calculate deltaTime, which is what we'll use from now on (Look down below for the UpdateDeltaTime() code)
  11.  
  12.     UpdateDeltaTime();
  13.  
  14.  
  15.     // Now, say you want something to happen every 20 seconds, like sending data.
  16.  
  17.     sendDataTimer += deltaTime // every second, at 1.0 to it
  18.  
  19.     if(sendDataTimer >= 20) // can replace 20 with sendDataInterval for easier editing later
  20.     {
  21.         //do something every 20 seconds, like
  22.         SendData(); //runs the SentData function below
  23.         sendDataTimer = 0; //reset the "every 20 seconds" timer, so it can start counting up to 20 again
  24.     }
  25.  
  26.    
  27.     // Are we awaiting a response? If so, add deltaTime to the timeouttimer.
  28.     if(awaitingResponse == true)
  29.     {
  30.         timeoutTimer += deltaTime;
  31.         if(timeoutTimer >= 3) //can replace 3 with timeoutPatience or something for easier editing later
  32.         {
  33.             //we didn't get a response! Bugger.
  34.             awaitingResponse = false;
  35.             //do whatever you want to do when you waited too long for a reponse
  36.         }
  37.     }
  38.  
  39. }
  40.  
  41. UpdateDeltaTime()
  42. {
  43.     unsigned long currentMillis = millis();
  44.     deltaTime = currentMillis - previousMillis ;
  45.     Serial.print(deltaTime); // deltaTime is how long the last loop() cycle took
  46.     previousMillis = currentMillis;
  47.  
  48.     deltaTime *= 0.001;
  49.  
  50.     if(deltaTime < 0) //this will happen when millis() resets
  51.     {
  52.         // you can do a few things here, you can just set deltaTime to 0, or remember what the last good deltaTime is
  53.         deltaTime = 0; // good enough
  54.     }
  55.  
  56. }
  57.  
  58. SendData()
  59. {
  60.     //send that data, and also resets the timeoutTimer;
  61.     timeoutTimer = 0;
  62.     awaitingResponse = true; // this allows the timeoutTimer to run
  63. }
Advertisement
Add Comment
Please, Sign In to add comment