我正在与Arduino合作开展一个非常重要的项目。我使用TimerOne触发定时器中断并使用micros()进行延迟(delayMicroseconds()导致的问题比下面解释的更糟)。程序正在向LED发送手动PWM信号,发送信号的误差小于8微秒(理想情况下,信号在每个周期内同时发送)非常重要。我的测试代码如下所示:
#include <TimerOne.h>
#include <SPI.h>
const int LED_PIN = 3;
const int CHIP_SELECT = 12;
const int PERIOD = 4000;
const double DUTY_CYCLE = .5;
const int HIGH_TIME = PERIOD * DUTY_CYCLE;
const int LOW_TIME = PERIOD - HIGH_TIME;
const int INITIAL_SIGNAL_DELAY = LOW_TIME / 2;
const int HIGH_TIME_TOTAL_DELAY = INITIAL_SIGNAL_DELAY + HIGH_TIME;
const int RESISTOR_VALUE = 255;
boolean triggered = false;
boolean data = false;
unsigned long triggeredTime;
unsigned long s;
unsigned long e;
boolean found;
int i = 0;
void setup()
{
s = micros();
Timer1.initialize(PERIOD);
Timer1.attachInterrupt(trigger);
pinMode(LED_PIN, 3);
pinMode(CHIP_SELECT, OUTPUT);
SPI.begin();
digitalWrite(CHIP_SELECT, LOW);
SPI.transfer(B00010001);
SPI.transfer(RESISTOR_VALUE);
digitalWrite(CHIP_SELECT, HIGH);
e = micros();
Serial.begin(115200);
Serial.print("s: ");
Serial.println(s);
Serial.print("e: ");
Serial.println(e);
}
void loop()
{
if(triggered)
{
while(micros() - triggeredTime < INITIAL_SIGNAL_DELAY)
{ }
s = micros();
digitalWrite(LED_PIN, data);
while(micros() - triggeredTime < HIGH_TIME_TOTAL_DELAY)
{ }
digitalWrite(LED_PIN, LOW);
data = !data;
triggered = false;
e = micros();
//micros();
if(s % 100 > 28 || s % 100 < 12)
{
found = true;
}
if(!found)
{
Serial.print("s: ");
Serial.println(s);
}
else
{
Serial.print("ERROR: ");
Serial.println(s);
}
//Serial.print("e: ");
//Serial.println(e);
}
}
void trigger()
{
triggeredTime = micros();
triggered = true;
}
(应该注意,发送的第一个信号总是xx20,通常是5020)。
因此,使用此代码,我最终会收到错误。我不知道为什么,但这个错误每次都在同一点发生:
.
.
.
s: 1141020
s: 1145020
s: 1149020
ERROR: 1153032
ERROR: 1157020
ERROR: 1161020
.
.
.
现在,真正奇怪的部分是如果我删除micros()之前的注释(e = micros()之后的micros()),没有错误(或者至少在前30个内没有错误)秒)。我想知道是否有人可以解释为什么会发生这种情况。我已经花了很多时间试图让时间正常工作,一切都运行良好,直到我遇到这个错误。任何帮助将非常感谢。谢谢!