1、使用MsTimer2库文件
使用之前需要先添加库
(1)实现功能
(2)代码
/*
MsTimer2 is a small and very easy to use library to interface Timer2 with
humans. It's called MsTimer2 because it "hardcodes" a resolution of 1
millisecond on timer2
For Details see: http://www.arduino.cc/playground/Main/MsTimer2
*/
#include <MsTimer2.h>
// Switch on LED on and off each half second
#if ARDUINO >= 100
const int led_pin = LED_BUILTIN; // 1.0 built in LED pin var
#else
const int led_pin = 13; // default to pin 13
#endif
void setup()
{
Serial.begin(115200);
pinMode(led_pin, OUTPUT);
MsTimer2::set(1000, flash); // 1000ms period
MsTimer2::start();
}
void loop()
{
Serial.println("loop send");
delay(2000);
}
void flash()
{
static boolean output = HIGH;
digitalWrite(led_pin, output);
output = !output;
Serial.println("Testing device connections...");
//Serial.print("\r\n");
}
2、使用程序设置固定扫描时间
(1)实现功能
(1)定义两个变量a、b,变量a是100毫秒自加一次、变量b是1秒自加一次。
(2)串口1秒输出一次
(2)代码
const long _100msTime = 100; // 100 milli seconds
unsigned long _100msLastTime;
const long _1000msTime = 1000; // 1000 milli seconds
unsigned long _1000msLastTime;
long a=0;
long b=0;
int count=0;
unsigned long startTime; // 用于记录开始时间
unsigned long endTime; // 用于记录结束时间
void startTimer()
{
startTime = millis(); // 记录开始时间
}
void stopTimer()
{
endTime = millis(); // 记录结束时间
}
unsigned long getElapsedTime()
{
return endTime - startTime; // 返回经过的毫秒数
}
void setup()
{
startTimer();
// 打开串口
Serial.begin(9600);
while (!Serial)
{
; //等待串口连接。仅本机USB口使用。
}
Serial.println("Serial is opened.");
}
void loop()
{
/*
stopTimer();
unsigned long elapsed = getElapsedTime(); // 获取经过的时间
Serial.print("StartTime is: ");
Serial.print(elapsed);
Serial.println(";");
delay(2000);
*/
TimeProc();
}
void TimeProc()
{
//1000ms执行一次
if ((millis() - _1000msLastTime) >= _1000msTime)
{
_1000msLastTime = millis( );
//
Serial.print("Counts a is: ");
Serial.print(a);
Serial.println(";");
Serial.print("Counts b is: ");
Serial.print(b);
Serial.println(";");
b++;
}
//100ms执行一次
if ((millis() - _100msLastTime) >= _100msTime)
{
_100msLastTime = millis( );
a++;
/*
//
if(count>10)
{
count=0;
a++;
}
count++;
*/
}
}