[英]C# Serial Communications issues with Arduino
I have been struggling with commincations speeds with some code. 我一直在用一些代码来应对通信速度。
So i want to increase the baud rate for both the code & Arduino. 所以我想提高代码和Arduino的波特率。 But if i leave the 9600 baud rate, the data stops sending & reciving properly.
但是,如果我离开9600波特率,数据将停止正确发送和接收。 So i set up a simple test program.
所以我建立了一个简单的测试程序。
Arduino Code: Arduino代码:
void setup()
{
Serial.begin(9600);
Serial.setTimeout(10);
}
void loop()
{
if (Serial.available())
{
String Data = Serial.readStringUntil('#');
if (Data == "Test")
{
Serial.println("Recived");
}
}
delay(1);
}
c# Code: C#代码:
SerialPort Port = new SerialPort("COM4", 9600);
Port.Open();
if (Port.IsOpen)
{
Port.Write("Test#");
System.Threading.Thread.Sleep(1000);
String Read = Port.ReadExisting();
Port.Close();
}
So running that String Read comes back with "Recived\\r\\n". 因此,运行该String Read将返回“ Recived \\ r \\ n”。 Change the baud rate to 19200 and it comes back with "".
将波特率更改为19200,然后返回“”。
Any ideas why this is occuring? 任何想法为什么会这样?
Edit: If I use the Arduino IDE's Serial Monitor Program, this works just fine regardless of baudrate used. 编辑:如果我使用Arduino IDE的串行监视器程序,则不管使用的波特率如何,它都可以正常工作。 Its as soon as i use c# that it that this issue occurs.
一旦我使用C#,就会发生此问题。 Which rules out hardware issues I believe.
我认为哪些排除了硬件问题。
Try sending a character at a time from the PC and use Serial.read() to read a character into a buffer in the arduino. 尝试一次从PC发送一个字符,然后使用Serial.read()将一个字符读入arduino的缓冲区中。 Sometimes sending the whole text from PC at high baud rate is too much for the arduino to handle.
有时,以高波特率从PC发送整个文本对于arduino来说太过分了。
Thankyou for you inputs. 谢谢您的投入。
Think i have found a solution, although not to clear about why. 认为我已经找到了解决方案,尽管不清楚原因。
I think it was due to the Serial.Avalible()
Command. 我认为这是由于
Serial.Avalible()
命令造成的。 Appears i needed to send though some data first to make it register the port is open. 似乎我需要先发送一些数据才能使其注册端口是开放的。
So modifying my C# code to this: Works 因此,将我的C#代码修改为:有效
SerialPort Port = new SerialPort("COM4", 9600);
Port.Open();
if (Port.IsOpen)
{
Port.Write("#");
Port.Write("Test#");
System.Threading.Thread.Sleep(1000);
String Read = Port.ReadExisting();
Port.Close();
}
Thanks a lot 非常感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.