Serial.WriteLine(“我的消息!“);附加

本文关键字:附加 我的消息 消息 WriteLine 我的 Serial | 更新日期: 2023-09-27 18:13:16

我正在尝试从c#应用程序发送消息到串口上的arduino。

但是它挂在WriteLine上。它永远不会结束,当我在arduino上读取缓冲区中存储的内容时,它就像我已经发送了100多次。

c# app上的代码

public void testSend()
    {
        if (mySerialPort.IsOpen)
        {
            //setup
            //mySerialPort.Open();
            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None;
            mySerialPort.RtsEnable = true;
            mySerialPort.WriteTimeout = 500;
            try 
            {
                mySerialPort.WriteLine("Sent from my c# app!");
            }
            catch(TimeoutException)
            {
                //Console.WriteLine("Timeout while sending data");
            }
            //mySerialPort.Close();
        }
        else 
        { 
            Console.WriteLine("Port already open!"); 
        }
    }

arduino上的代码(供参考和清除)

    void setup()
    {
        //Initialize serial and wait for port to open:
        Serial.begin(9600);
        while (!Serial)
        {
            ; // wait for serial port to connect. Needed for native USB
        }
    }
    char* buf = malloc(1024);
    int ReciveData()
    {
        if (Serial.available())
        {
            // read the incoming bytes:
            String temp = Serial.readString();
            if (temp.length() > 0)
            {
                temp.toCharArray(buf, temp.length() + 1);
            }
        }
    }
    void loop()
    {
        Serial.print("Sent from arduino!");
        Serial.println(buf);
        delay(1000);
        ReciveData();
    } 
}

这就是它的样子。这里有4条消息,每个发送都以"从arduino发送!"开始。当我读到的时候。你可以看到在第1行和第2行,一切正常但是当我启动c#应用程序时,它会显示夏威夷

Sent from arduino!Sent from serial terminal!
Sent from arduino!Sent from serial terminal!
Sent from arduino!Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from arduino!Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!

Serial.WriteLine(“我的消息!“);附加

不知道为什么。但是当我试图在字符串末尾添加'0时,它工作了。

        try 
        {
            mySerialPort.WriteLine("Sent from my c# app! '0");
        }

在c '0中是字符串结束符。如果没有它,读取将不知道字符数组已经结束。

mySerialPort.WriteLine方法将发送您指定的字符串+ mySerialPort.NewLine值,在您的情况下是默认值- System.Environment.NewLine(即"'r'n")。

在使用WriteLine(以及ReadLine)之前-指定协议EOL字符,在您的情况下:

mySerialPort.NewLine = "'0"

并且不需要在每次书写时手动添加EOL字符(并且会错过WriteLine而不是Write的目的)