2012-06-16 70 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这就是全部。现在它可以工作。