Monday, 10 December 2018

millis() function - basic - 1 LED blink sketch

 The millis() function is a time function.
It is similar to the delay function, however it has the advantage that the program's execution doesn't stall until the delay is over. That is, its good at multitasking.

 Millis is actually running in the background all the time. It's a clock.
It returns the number of milliseconds that has passed since the current program was started.
It counts for approximately 49 days, till it overflows and goes back to zero.
Then starts all over again. 
 
It is important to remember that it returns values in unsigned long data types.
Thus you can't use data types like "int"

Below is a link to the classic blink sketch that uses delay. 

Next, is the same program using the millis function 
 
 // **********************
// Classic Blink Sketch - using the millis function
unsigned long startms =0;
unsigned long previousMS = 0; //time since last change of state
unsigned long interval=1000;

#define LED1 8

int LED1_state=0;

void setup() {
  pinMode(LED1, OUTPUT);
}

void loop() {
  startms = millis();
  if (startms - previousMS > interval){
   previousMS = startms;
    if (LED1_state==0) LED1_state=1; else LED1_state=0;
    digitalWrite(LED1,LED1_state);
  }
}

//*****************
In order to use Millis for timing, we need to do these things:
1. Record the time (start) when the action started or took place.
2. Record the current time.
3. Choose a period of time to recheck the millis time.
4. check at frequent intervals whether the required period has elapsed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 At the start of the program declare 3 global variables, as follows
Code: [Select]

unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 1000;  //the value here is a number of milliseconds, ie 1 second
 

 
Links
 
 

No comments:

Post a Comment