簡體   English   中英

C#與arduino的串行通訊

[英]C# Serial communcation with arduino

我試圖將字符串從arduino(leonardo)發送到C#程序。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;

namespace ConsoleApplication2
{
class Program
{

    static void Main(string[] args)
    {
        SerialPort mySerialPort = new SerialPort("COM7");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;


        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
    }
}
}

這是我從msdn示例中復制的代碼,以嘗試了解它的作用。 我下面的arduino代碼只是通過com端口發送hello世界,延遲為1000。

void setup ()
{

 Serial.begin(9600);

 }


void loop(){

 Serial.println("Hello World");
 delay(1000);
}

我的arduino正在使用C7程序中定義的COM7。 當我運行機器人程序時,C#程序永遠不會進入數據接收事件處理程序。 因此沒有收到任何數據。 我真的想讓tis工作:)

親切的問候

我將代碼切換到Windows窗體應用程序,但仍無法正常工作。 然后,我發現了一個關於串行通信話題C#關於Arduino的萊昂納多這里

我必須這樣做:

        serial.DtrEnable = true;
        serial.RtsEnable = true;

我認為我的問題已經解決。

控制台應用程序沒有消息循環,因此自然不會響應事件。 您只有一個線程,它將被阻塞在Console.ReadKey() 可以使用從串行端口進行的同步讀取,或者,如果您希望使用基於事件的模型,請將此代碼移至基於Windows的應用程序。

有關同步示例, 請參見以下MSDN示例

while (_continue)
{
    try
    {
        string message = _serialPort.ReadLine();
        Console.WriteLine(message);
    }
    catch (TimeoutException) { }
}

以上僅是摘錄-完整示例演示了設置超時值等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM