Difference between revisions of "Lesson 21--Microduino "Use Timer Interrupt""
From Microduino Wiki
Line 1: | Line 1: | ||
− | {{Language|Microduino_定时器中断的使用}} | + | {{Language|第二十一课--Microduino_定时器中断的使用}} |
{| style="width: 800px;" | {| style="width: 800px;" | ||
|- | |- |
Latest revision as of 15:15, 2 March 2014
Language: | English • 中文 |
---|
ContentsObjectiveThis lesson will introduc Microduino's timer interrupt. Use the timer interrupt to control LED by IO port 13. The time slot is 500ms. EquipmentMicroduino-Core Microduino-FT232R
Experiment 1Use library MsTimer2
// 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()
{
} ResultThe state of LED changs every 500ms. Experiment 2Use function millis()
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
|