簡體   English   中英

使用C#讀取arduino發送到串行端口的信息

[英]Reading Info sent by arduino to Serial Port with C#

我正在嘗試從arduino讀取簡單的傳感器讀數。 arduino連接到COM3(用於發送數據和對arduino進行編程)。 C#程序非常簡單,它嘗試讀取arduino發送的內容。 問題:當另一端(分別為C#或arduino)已經打開COM3端口時,我無法用C#或arduino打開它。 只是發送而沒有打開不會產生任何結果。 您應該如何“連接”它們? 我的理解是,兩個設備都以相同的波特率打開端口,然后您可以發送和讀取數據。 當我嘗試打開時,我將在C#端獲得一個UnauthorizedAccess或在arduino端獲得一個“無法打開序列”。

Arduino C代碼:

#include <DHT.h>

#define DHTPIN A4
#define DHTTYPE DHT11
#define THERPIN A0

DHT dht(DHTPIN,DHTTYPE);   
String hum="Humidity:";
String temptext="Temp:";
String semi=";";

void setup() {  
    Serial.begin(9600);
    dht.begin();
    pinMode(A0,INPUT);
}    
void loop() {   
    float humidity = dht.readHumidity();
    delay(300);
    float temp = dht.readTemperature();
    delay(300);


    if (isnan(humidity)||isnan(temp))
    {
      Serial.println("Fehler beim Lesen(NAN)");
      delay (5000);
   }else
    {
      Serial.print(temp + semi);
      Serial.print(humidity);
      Serial.flush();
      delay(1000);  
    }
}

C#代碼

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

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {    
            SerialPort serialPort1;
            serialPort1 = new SerialPort();
            serialPort1.PortName = "COM3";
            serialPort1.BaudRate = 9600;
            serialPort1.DtrEnable = true;
            REPEAT:
            if (serialPort1.IsOpen)
            {
                string reading = serialPort1.ReadLine();
                Console.WriteLine(reading);
                serialPort1.Close();                   
            }
            else
            {
                Console.WriteLine("closed,opening");
                serialPort1.Open();
                goto REPEAT;    
            }    
        }
    }
}

在搜索解決方案時,總是有另一個程序已經在使用COM端口,但這不是我需要傳達的信息嗎? 顯然,據我所知,arduino必須使用與C#應用程序相同的COM端口。

謝謝

您的代碼將永久打開和關閉串行端口。 這是行不通的,因為當.NET代碼關閉連接時,Windows內部將異步關閉端口。 實際關閉端口可能需要幾秒鍾。 這就是程序幾乎立即被阻止的原因。

在程序開始時僅打開一次連接。

此外:不惜一切代價避免GOTO語句。 埃德加·迪克斯特拉(Edgar Dijkstra)多年前寫了一篇反對其使用的論文: 認為有害的陳述

暫無
暫無

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

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