“Lesson 21--Microduino "Use Timer Interrupt"”的版本间的差异
(未显示同一用户的2个中间版本) | |||
第1行: | 第1行: | ||
− | {{Language| | + | {{Language|第二十一课--Microduino_定时器中断的使用}} |
{| style="width: 800px;" | {| style="width: 800px;" | ||
|- | |- |
2014年3月2日 (日) 15:15的最新版本
Language | English |
---|
目录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
|