2011-11-27 73 views
9

我開發了一個通過串口發送Arduino數據的應用程序,但我無法理解如何在Arduino上接收它。我通過Arduino的串行端口發送一個字符串,Arduino接收它,但它在我的代碼中不起作用(在Arduino上,我每次接收一個字節)。如何從PC接收數據到Arduino?

更新:它的工作;)

在C#中的代碼,將數據發送:

using System; 
using System.Windows.Forms; 

using System.Threading; 
using System.IO; 
using System.IO.Ports; 

pulic class senddata() { 

    private void Form1_Load(object sender, System.EventArgs e) 
    { 
     //Define a serial port. 
     serialPort1.PortName = textBox2.Text; 
     serialPort1.BaudRate = 9600; 
     serialPort1.Open(); 
    } 

    private void button1_Click(object sender, System.EventArgs e) 
    { 
     serialPort1.Write("10"); //This is a string. The 1 is a command. 0 is interpeter. 
    } 
} 

Arduino的代碼:

我有更新代碼

#include <Servo.h> 

Servo servo; 
String incomingString; 
int pos; 

void setup() 
{ 
    servo.attach(9); 
    Serial.begin(9600); 
    incomingString = ""; 
} 

void loop() 
{ 
    if(Serial.available()) 
    { 
     // Read a byte from the serial buffer. 
     char incomingByte = (char)Serial.read(); 
     incomingString += incomingByte; 

     // Checks for null termination of the string. 
     if (incomingByte == '0') { //When 0 execute the code, the last byte is 0. 
      if (incomingString == "10") { //The string is 1 and the last byte 0... because incomingString += incomingByte. 
       servo.write(90); 
      } 
      incomingString = ""; 
     } 
    } 
} 
+0

也許更好的地方問:http://electronics.stackexchange。com/ – vikingosegundo

回答

3

有些東西讓我的眉毛加薪:

serialPort1.Write("1"); 

這將寫正好一個字節中,1,但沒有換行,並沒有尾隨NUL字節。 但在這裏你正在等待一個額外的NULL字節:

if (incomingByte == '\0') { 

您應該使用WriteLine,而不是Write,並等待\n而不是\0

這有兩個副作用:

第一:如果有一些緩衝構造,則存在一定的機率,比新線將所緩衝的數據推到Arduino。爲了確保你必須在MSDN上查看文檔。

第二:這使得你的協議只有ASCII。這對於更容易的調試非常重要。然後,您可以使用普通終端程序像超級終端或HTerm(編輯),甚至串行監視器中的Arduino IDE本身(編輯)調試你的Arduino的代碼,而不必擔心在你的C#代碼中的bug。當Arduino代碼工作時,您可以專注於C#部分。除以等。

編輯:挖掘出我自己的Arduino之後,我注意到另一件事:

incomingString += incomingByte; 
.... 
if (incomingByte == '\n') { // modified this 
    if(incomingString == "1"){ 

這當然會不按預期工作,因爲字符串將包含「1 \ n」在這一點上。您可以比較「1 \ n」或在if之後移動+=行。

+0

不要工作! :( – FredVaz

+0

您是否嘗試過用於調試Arduino的終端程序? –

+0

串行監視器?是的,我嘗試。 – FredVaz

1

你可以或者嘗試使用Firmata library - 這是有關於Arduino的標準固件和.NET

我相信它管理的一種更好的方式,Firmata 2.0+具有I2C和伺服控制的支持。

http://firmata.org/

相關問題