我有一个计时器,它应该以我的心率(以节拍/分钟为单位)生成Console.Beep
。我使用以下简单公式计算 C#计时器中的Timer.Interval
:
ServerVarValues = new ws ServerVarValues();
this.timerHeartBeatSound = new System.Windows.Forms.Timer(this.components);
public class ServerVarValues
{
public int HR;
public DateTime LastHRUpdate;
public int SpO2;
public DateTime LastO2Update;
public double Temperature;
public DateTime LastTempUpdate;
}
//... I plug in my heart rate to calculate my new timer interval...
int tVal = (int)Math.Round((ws.HR / 60.0) * 1000,0);
timerHeartBeatSound.Interval = tVal;
// and with the new interval, the timer generates a Tick Event that runs this
private void PlayHeartBeatSound(object sender, EventArgs e)
{
Console.Beep();
}
我正在从可穿戴设备上读取心率。问题是每次我的HR改变时,当我改变计时器的间隔时,计时器会被重置。因此,我经常听到打嗝,而不是平稳改变心率声音。
每次心率变化时如何避免重置计时器的想法?
答案 0 :(得分:2)
是的,这是设计的。当您更改Interval属性并且它不相同时,Timer会自行重置。你无法改变这种行为。
所以你必须做的是不更新Interval。直到下一个Tick发生。哪个好,心跳很快就会发生。你需要另一个变量:
public class ServerVarValues {
public int NextInterval;
// etc...
}
在启动计时器或更新心率值时初始化它:
...
int tVal = (int)Math.Round((ws.HR / 60.0) * 1000,0);
if (timerHeartBeatSound.Enabled) ws.NextInterval = tval;
else {
ws.NextInterval = 0;
timerHeartBeatSound.Interval = tval;
}
在Tick事件处理程序中,您需要检查是否必须使新间隔生效:
private void PlayHeartBeatSound(object sender, EventArgs e)
{
if (ws.NextInterval != 0) timerHeartBeatSound.Interval = ws.NextInterval;
ws.NextInterval = 0;
Console.Beep();
}
答案 1 :(得分:0)
尝试以下操作,除了“ASecond”而不是使用与当前心率相对应的毫秒数。这将根据当前速率重新计算直到下一个节拍的毫秒数,并为每个节拍执行此操作。我希望它更顺畅。
DateTime LastTime = DateTime.Now;
...
DateTime NextTime = LastTime + ASecond;
// Just in case we have gone past the next time (perhaps you put the system to sleep?)
if (DateTime.Now > NextTime)
NextTime = DateTime.Now + ASecond;
TimeSpan Duration = NextTime - DateTime.Now;
LastTime = NextTime;
timer1.Interval = (int)Duration.TotalMilliseconds;