C#和Arduino超时功能 [英] C# and Arduino Timeout function
问题描述
我目前正在为一个项目使用Arduino IDE和C#环境.主要思想是从某些变量写入和读取值.在更改变量以确认更改正确完成或发生通信错误后,我想实现超时.有人可以通过链接或PDF信息帮助我了解实现此功能的方法吗?这是代码的一部分:
C#
private void connectToArduino()
{
isConnected = true;
string selectedPort = comboBox1.GetItemText(comboBox1.SelectedItem);
port = new SerialPort(selectedPort, 115200, Parity.None, 8, StopBits.One);
port.Open();
port.Write("#START\n");
button1.Text = "Disconnect";
label5.Text = "Ready!";
label5.ForeColor = Color.Blue;
label7.Text = "Ready!";
label7.ForeColor = Color.Blue;
textBox5.Text = "0";
textBox6.Text = "0";
textBox8.Text = "0";
textBox9.Text = "0";
}
private void disconnectFromArduino()
{
isConnected = false;
port.Write("#STOP\n");
port.Close();
button1.Text = "Connect";
label5.Text = "No ready";
label5.ForeColor = Color.Red;
label7.Text = "No ready";
label7.ForeColor = Color.Red;
textBox5.Text = "0";
textBox6.Text = "0";
textBox8.Text = "0";
textBox9.Text = "0";
}
private void button1_Click_1(object sender, EventArgs e)
{
if (!isConnected)
{
connectToArduino();
}
else
{
disconnectFromArduino();
}
}
private void Aplicar1_Click(object sender, EventArgs e)
{
if (isConnected)
{
port.WriteLine("#SP" + textBox5.Text + "#\n");
}
else
{
MessageBox.Show("Connect COM Port");
}
}
Arduino
boolean isConnected = false;
String inputString = "";
boolean stringComplete = false;
String commandString = "";
int led1Pin = 10;
int led2Pin = 9;
int led3Pin = 8;
int led4Pin = 7;
int button = 13;
int buttonstate;
String Command, Value, Valuenum, Jump, Request;
void setup()
{
Serial.begin(115200);
}
int numero1;
int numero2;
int numero3;
int numero4;
void loop() {
if(stringComplete) {
stringComplete = false;
getCommand();
if(commandString.equals("#SP")) {
numero1 = getNumToPrint();
compareNum(numero1);
Command = String ("SP");
Value = String ("OK");
Jump = String ("\n");
Serial.print(Command + Value);
}
推荐答案
添加一些多行 textBox10
以便在其中写入从模块接收到的消息.这将有助于调试. MessagBox
不是调试的好方法.
Add some multiline textBox10
to write there messages received from the module. It would be helpful in debugging. MessagBox
is not a good solution for debugging.
PortReaderLoop
was made with help of SerialPort
documentation.
我排除了未更改的方法.
I've excluded not changed methods.
private void connectToArduino()
{
isConnected = true;
string selectedPort = comboBox1.GetItemText(comboBox1.SelectedItem);
port = new SerialPort(selectedPort, 115200, Parity.None, 8, StopBits.One);
port.ReadTimeout = 500;
port.WriteTimeout = 500;
port.Open();
port.Write("#START\n");
button1.Text = "Disconnect";
label5.Text = "Ready!";
label5.ForeColor = Color.Blue;
label7.Text = "Ready!";
label7.ForeColor = Color.Blue;
textBox5.Text = "0";
textBox6.Text = "0";
textBox8.Text = "0";
textBox9.Text = "0";
Task.Run(() => PortReaderLoop());
}
private readonly IProgress<string> messageCallback = new Progress<string>(s =>
{
textBox10.Text += s + "\r\n";
});
private readonly IProgress<string> errorCallback = new Progress<string>(s =>
{
MessageBox.Show(s);
});
// continuously reads the input and fires callback for each received line
private void PortReaderLoop()
{
try
{
while (isConnected)
{
try
{
string message = port.ReadLine();
messageCallback.Report(message);
}
catch (TimeoutException) { } // nothing received
}
}
catch (InvalidOperationException) { } // port is not open
}
// the answer to your question is this method and timeouts in connectToArduino()
private async Task PortWriteAsync(string message)
{
try
{
await Task.Run(() =>
{
port.WriteLine(message);
});
}
catch (Exception ex)
{
errorCallback.Report(ex.Message);
}
}
// async to keep UI responsive while writing to Port
private async void Aplicar1_Click(object sender, EventArgs e)
{
if (isConnected)
{
Aplicar1.Enabled = false;
await PortWriteAsync("#SP" + textBox5.Text + "#\n");
Aplicar1.Enabled = true;
}
else
{
errorCallback.Report("Connect COM Port");
}
}
IProgress
有助于在UI线程中执行某些操作,因为从其他(合并的)线程或任务中进行更新是不安全的.
IProgress
helps to execute something in the UI Thread because updating it from the other (pooled) Threads or Tasks is unsafe.
如果您对 async/await
感兴趣,请参考文档
If you're interested in async/await
please refer to the documentation
我没有测试代码,因为我没有这样的模块.
这篇关于C#和Arduino超时功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!