您好,我有麻烦与我的机器人轮椅控制的c#应用程序。我可以通过按钮来控制汽车,这是好的。问题由键盘字母控制。当我按下并按住W,A,S,D时,c#不断地向arduino发送命令,它可以产生电机冻结和连续驱动。问题是,我可以修改c#代码,只发送一个命令(而不是每秒连续发送大约10次相同的命令),就像我按下按钮一样。
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.W:
Arduino.Write("R");
break;
case Keys.S:
Arduino.Write("A");
break;
case Keys.A:
Arduino.Write("I");
break;
case Keys.D:
Arduino.Write("S");
break;
}
}发布于 2014-09-07 19:03:19
你有没有想过实现一个计时器来导致写入Arduino之间的延迟?您可以将按下键的时间与返回特定时间段的函数进行比较(如果已过,则返回true或false ),如果为true,则可以调用Arduino.Write函数。尽管该函数将连续调用,但写入Arduino的时间将根据计时器的不同而延迟。
问题的格式不同,但我相信这可能会对您有所帮助:How can I get rid of character repeat delay in C#?
发布于 2014-09-07 19:26:35
试试这个:
// Add this before all the methods
private bool canSend = true;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
var timer = new Timer();
timer.Interval = 5000; // Example value, multiply number of seconds by 1000 to get a value
timer.Tick += new EventHandler(TimerTick);
if (!canSend) return;
switch (e.KeyCode)
{
case Keys.W:
Arduino.Write("R");
break;
case Keys.S:
Arduino.Write("A");
break;
case Keys.A:
Arduino.Write("I");
break;
case Keys.D:
Arduino.Write("S");
break;
}
canSend = false;
timer.Start();
}
private void TimerTick(object sender, EventArgs e)
{
canSend = true;
} 它所做的是检查它是否可以发送命令。如果可以,它将启动一个新的计时器(在我创建的示例中为5秒),并重新设置bool,以便可以再次发送。
发布于 2014-09-07 20:56:00
最好的解决方案是在特定时间设置超时或锁定资源(使用互斥锁/锁)
private bool isArduinoFree=true;
private int _timeOut=500; //equal to half second
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (isArduinoFree)
{
isArduinoFree=false;
switch (e.KeyCode)
{
case Keys.W:
Arduino.Write("R");
break;
case Keys.S:
Arduino.Write("A");
break;
case Keys.A:
Arduino.Write("I");
break;
case Keys.D:
Arduino.Write("S");
break;
}
Thread.Sleep(_timeOut);
_isArduinoFree=true;
}
}注意:如果您使用睡眠,它将冻结您可以创建一个任务,并启动它。
https://stackoverflow.com/questions/25709422
复制相似问题