我需要一些帮助,试图让计时器有点模糊。我想使用固定的时间间隔,如下所示:
____|_______|____|_____|_________|_____|___|_______|
管道是事件发生的地方,下划线是数组中的延迟:
int myIntervals = { 1000, 2000, 750, 850, 1200, 850, 500, 1000};
但值是任意的。
我想为事件创建一个轻微的随机性,但不允许随机性影响整体时间:
___*|*_____*|*__*|*___*|*_______*|*___*|*_*|*_____*|
其中随机性被描述为星号所包含的时间。
因此事件总是发生在间隔+ - 随机延迟:
int fuzzyPeriod = random(-75,75);
我已经对此进行了实验,但无济于事......当模糊周期为负时,我发现自己处于递归状态,或者像这样我得到了一个毫秒()溢出问题,显然。 / p>
int sequence[] = {1000, 750, 950, 1150, 1200, 1500, 1000, 1900, 2000};
unsigned int index;
unsigned long startMillis = 0;
unsigned int fuzzy = sequence[0];
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop()
{
if (startMillis < millis()) // will have rollover issues <<<<<<<
{
if (millis() - startMillis >= fuzzy)
{
digitalWrite(13, !digitalRead(13));
startMillis += sequence[index]; // advance startMillis by the last interval used
index++;
if (index >= sizeof(sequence) / sizeof(sequence[0]))
{
index = 0;
Serial.println("Restarted Sequence");
}
fuzzy = sequence[index] + random(-75, 76); // arbitrary offset needs to be positive or negative
Serial.print("fuzzy = ");
Serial.println(fuzzy);
}
}
}
我希望我做得很好解释......我不能为我的生活做到这一点,我知道我已经到了需要一点帮助的地步!
答案 0 :(得分:0)
这样的事情:
unsigned int index;
unsigned long nextMillis;
int prevFuzzy = 0;
int fuzzy = 0;
void setup()
{
//...
nextMillis = millis();
}
void loop()
{
if (millis() >= nextMillis)
{
fuzzy = random(-75, 76);
// compensate for previous deviation and add new one
nextMillis += sequence[index] - prevFuzzy + fuzzy;
fuzzy = prevFuzzy;
// or just:
// fuzzy = random(-75, 76) - fuzzy
// nextMillis += sequence[index] + fuzzy;
index++;
if (index >= sizeof(sequence) / sizeof(sequence[0]))
{
index = 0;
}
// Do stuff
}
}
答案 1 :(得分:0)
首先,您必须使用无符号长整数毫秒来正确计算溢出。
然后我还在不同的地方初始化变量,并使用不同的值
初始化int sequence[] = {1000, 750, 950, 1150, 1200, 1500, 1000, 1900, 2000};
unsigned int index = 0;
unsigned long startMillis;
unsigned int fuzzy = sequence[0] + random(-75, 76);
#include <limits.h>
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
randomSeed(analogRead(0));
startMillis = millis();
}
void loop()
{
long MilliDiff;
if (startMillis <= millis())
MilliDiff = millis() - startMillis;
else
MilliDiff = ULONG_MAX - startMillis + millis();
if (MilliDiff >= fuzzy)
{
digitalWrite(13, !digitalRead(13));
startMillis += sequence[index]; // advance startMillis by the last interval used
index++;
if (index >= sizeof(sequence) / sizeof(sequence[0]))
{
index = 0;
Serial.println("Restarted Sequence");
}
fuzzy = sequence[index] + random(-75, 76); // arbitrary offset needs to be positive or negative
Serial.print("startMillis = ");
Serial.print(startMillis);
Serial.print(", sequence = ");
Serial.print(sequence[index]);
Serial.print(", fuzzy = ");
Serial.println(fuzzy);
}
}
此代码似乎正在我的Uno
上运行