1
我想創建一個Arduino Leonardo和C#之間的通信。Arduino和C#串行端口「崩潰」
剛纔,Arduino的軟件發送一個簡單的消息(環路)串行端口:
void setup() {
Serial.begin(9600);
analogReference(INTERNAL);
}
void loop() {
Serial.println("test");
delay(500);
}
C#只嘗試讀取這些信息,並打印出來的外殼:
public class Program
{
private SerialPort mySerialPort;
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine("PORTS: " + String.Join(" ", p.getSerialPortsList())+ ", enter to start.");
Console.Read();
p.SerialRead("COM6");
}
public String[] getSerialPortsList()
{
string[] ports = SerialPort.GetPortNames();
return ports;
}
public void SerialRead(String com)
{
mySerialPort = new SerialPort(com, 9600, Parity.None, 8, StopBits.One);
Console.Read();
Console.WriteLine("Incoming Data:");
SerialRead sr = new SerialRead();
Thread rs = new Thread(sr.StartRead);
sr.SetMySerialPort(mySerialPort);
rs.Start();
while (!rs.IsAlive);
Console.Read();
sr.SetSuspendThread(true);
rs.Join();
}
}
public class SerialRead
{
private Boolean suspendThread = false;
SerialPort mySerialPort;
public void StartRead()
{
mySerialPort.Open();
Thread.Sleep(500);
int i = 0;
while (!suspendThread)
{
i++;
Console.WriteLine(i + ": " + mySerialPort.ReadLine());
Thread.Sleep(500);
}
}
public void SetMySerialPort(SerialPort mysp){ mySerialPort = mysp; }
public void SetSuspendThread(Boolean a){ suspendThread = a; }
}
這個C#軟件的輸出取決於。如果我在Arduino IDE上使用串行監視器,那麼我會正確接收字符串的流(每個500毫秒一個)。否則,C#軟件會凍結。有時候,我會收到一些字符串,我們可以看到this figure;但幾乎所有的時間,軟件不給任何字符串,我們可以看到here。之後,軟件凍結(因此,如果我按下輸入shell不響應)。
您能否建議一個解決方案以獲得流暢的字符串流,並且 - 從而讀取Arduino在串行端口上發送的每條消息?
我使用Window 10 x64作爲操作系統和COM6(它是一個USB 2.0)。