Lesson 21--Microduino "Use Timer Interrupt"

来自Microduino Wikipedia
跳转至: 导航搜索
Language English

Objective

This lesson will introduc Microduino's timer interrupt. Use the timer interrupt to control LED by IO port 13. The time slot is 500ms.

Equipment

Microduino-Core Microduino-FT232R

  • Other hardware equipment
    • Breadboard Jumper one box
    • Breadboard one piece
    • LED one
    • 220Ω resistor one
    • USB Data cable one

Experiment 1

Use library MsTimer2

  • Example:
// LED connects to Pin 13
#include <MsTimer2.h>               //Timer's head file

void flash()                        //The interrupt service function
{                        
  static boolean output = HIGH;
  digitalWrite(13, output);
  output = !output;
}
void setup()
{
  pinMode(13, OUTPUT);
  MsTimer2::set(500, flash);        //Set interrupt function, the timer is 500ms
  MsTimer2::start();                //Start timer
}

void loop()
{
}

Result

The state of LED changs every 500ms.

Experiment 2

Use function millis()

  • Example program
unsigned long ledOn=500,ledOff=500; //Define the timer 500ms
int ledStatus;                      //Define LED state, HIGH or LOW
void setup()
{
	pinMode(13,OUTPUT);
	digitalWrite(13,HIGH);
	ledStatus=HIGH;
}
void loop()
{
    unsigned long nowtime=millis(); //Get the system current runned time
    if(ledStatus==HIGH)             //Check LED state
    {
      if(nowtime>ledOn)             //Check if time out happened
      {
        ledOn=nowtime;              //Record time, the first time is 500ms
        ledOff=nowtime+500;         //Calculate next time when LED state change
        digitalWrite(13,LOW);       //LED off
        ledStatus=LOW;              //Record current LED state, used next time     
    }
}

else{      
	if(nowtime>ledOff)
	{   
		ledOff=nowtime;
		ledOn=nowtime+500;
		digitalWrite(13,HIGH);
		ledStatus=HIGH;
	}
}
}

Result

  • Use the function mills()has the same result. LED state changed every 500ms.
  • Function mills() can achieve the functionality of interrupt. The function of mills() is to obtain the system running time length, and the unit is ms. Up range is 9 hours 22 minutes, if beyond this time slot will start from zero. The return value of a function is unsigned long type.
  • Players can use function mills() according to actual situation. The advantages of using function mills()is that take up the entire program running time is short, if use time delay function, in the delay time, the CPU can't do anything else.