2012-06-16 72 views
3

我想將出現在Arduino中的數據傳輸到我的C#應用​​程序,並且不知道我的代碼中有什麼問題。 這裏談到的Arduino代碼:串口+ C#數據接收問題

int switchPin = 7; 
int ledPin = 13; 
boolean lastButton = LOW; 
boolean currentButton = LOW; 
boolean flashLight = LOW; 

void setup() 
{ 
    pinMode(switchPin, INPUT); 
    pinMode(ledPin, OUTPUT); 
} 

boolean debounce(boolean last) 
{ 
    boolean current = digitalRead(switchPin); 
    if (last != current) 
    { 
    delay(5); 
    current = digitalRead(switchPin); 
    } 
    return current; 
} 

void loop() 
{ 
    currentButton = debounce(lastButton); 
    if (lastButton == LOW && currentButton == HIGH) 
    { 
    Serial.print("UP"); 

    digitalWrite(ledPin, HIGH); 
    } 
    if (lastButton == HIGH && currentButton == LOW) 
    { 
    Serial.print("DOWN"); 

    digitalWrite(ledPin, LOW); 
    } 

    lastButton = currentButton; 
} 

正如你可以看到,當按下按鈕這個簡單的草圖發送消息到端口。 我創建了一個控制檯C#應用程序接收數據:

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

namespace ArduinoTestApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      SerialPort port = new SerialPort("COM3", 9600); 
      port.Open(); 
      string lane; 
      while (true) 
      { 
       lane = port.ReadLine(); 

       Console.WriteLine(lane); 
      } 

     } 
    } 
} 

但是,當我按下按鈕控制檯仍然是空的。 請告訴我什麼是錯的!

+2

with port.ReadLine()我認爲你需要發送一個CR或LF或兩者都可以? – kenny

+0

@kenny:你的意思是「CR還是LF」?你能寫一些更多的信息嗎? :) – omtcyfz

+0

你缺少port.Close()?它看起來像你的代碼不釋放潛在的未託管代碼的資源。 –

回答

2

這一切都很簡單。我忘了寫

Serial.begin()

:d這就是全部。現在它可以工作。