Lesson 21--Microduino "Use Timer Interrupt"
Jasonsheng(讨论 | 贡献)2014年2月19日 (三) 13:18的版本 (Created page with "{| style="width: 800px;" |- | ==Objective== This lesson will introduc Microduino's timer interrupt. Use the timer interrupt to control LED by IO port 13. The time slot is 500m...")
目录ObjectiveThis 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
|