简体   繁体   English

从Arduino / C#应用程序读取和发送串行数据

[英]Read and Send serial data from Arduino / C# application

I have a program that allows several Arduinos to communicate via Serial Port. 我有一个程序,允许几个Arduino通过串行端口进行通信。 For example if Arduino1 want to communicate with Arduino3 the user sends a string from Arduino1 and this string appears on Arduino3 and so on. 例如,如果Arduino1要与Arduino3通信,则用户从Arduino1发送一个字符串,并且该字符串出现在Arduino3上,依此类推。 This is working good with SerialMonitor . 使用SerialMonitor可以很好地工作。

The problem is when I try to do the same in my C# application (nothing appears). 问题是当我尝试在C#应用程序中执行相同操作时(什么都没有出现)。 I tryed this: 我尝试了这个:

//(...)
comPort1.Open();
//(...)
private void comPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string inData = comPort1.ReadLine();
    msgBoxLog.AppendText(inData); // msgBoxLog = textBox with data received/sent
}
//(...)
private void sendButton_Click(object sender, EventArgs e)
{
    string my_str = "my string";
    msgBoxLog.AppendText(my_str + "\r\n");
    comPort1.WriteLine(my_str + "\r\n");
}

Some notes: 一些注意事项:

  • RtsEnable and DtrEnable are both active RtsEnableDtrEnable均处于活动状态
  • BaudRate (Arduino / C#) = 1200 波特率(Arduino / C#)= 1200

Is baudrate value a problem? 波特率值有问题吗? I must use this value but I'm not sure if it is accepted by C#. 我必须使用该值,但不确定C#是否接受该值。 I also tryed something like this but with no success. 我也tryed像这样 ,但没有成功。

I have a vague memory about not being able to access UI controls through the dataReceived event. 我对不能通过dataReceived事件访问UI控件有一个模糊的记忆。 Try this. 尝试这个。

private void comPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string inData = comPort1.ReadLine();
    this.Invoke(new EventHandler(processData));
}

private void processData(object sender, EventArgs e)
{
    msgBoxLog.AppendText(inData);
}

Do you have proper event handler enabled, like in this example? 您是否已启用适当的事件处理程序,如本例所示?

mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx http://msdn.microsoft.com/zh-CN/library/system.io.ports.serialport.datareceived.aspx

ps I'm using "dumb" delay in my software, between write and read serial port, and it's worked fine. ps我在写和读串行端口之间的软件中使用了“哑”延迟,并且工作正常。 Like this: 像这样:

serialPort1.Write(Data, 0, Data.Length);

System.Threading.Thread.Sleep(500);

try
{
    serialPort1.Read(Data2, 0, Data2.Length);
}
catch (TimeoutException)
{
    errorProvider1.SetError(maskedTextBox1, "timeout");
}
catch (ArgumentNullException)
{
    errorProvider1.SetError(maskedTextBox1, "no answer");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM