2016-07-07 30 views
0

嗨,大家好,我需要你們對我的項目的幫助。我在C#程序中有2個文本框(類型字符串),我需要使用Serial.Port將這些數字發送給Arduino。到目前爲止,我必須將其中一個值發送給arduino,但如果輸入「1200」arduino並顯示:1,2,0,0我需要「1200」,則效果不佳。我如何從C#發送2個值到Arduino? arduino如何讀取這些值(x和y)?從C#到Arduino使用Serial.Port

C#

using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 
    using System.Windows.Forms; 
    using System.IO.Ports; // necessário para ter acesso as portas 

    namespace interfaceArduinoVS2013 

{ 
    public partial class Form1 : Form 
    { 

     string RxString; 

     public Form1() 
     { 
      InitializeComponent(); 
      timerCOM.Enabled = true; 
     } 

     private void atualizaListaCOMs() 
     { 
      int i; 
      bool quantDiferente; //If there are more ports 

      i = 0; 
      quantDiferente = false; 

      //if there are new ports 
      if (comboBox1.Items.Count == SerialPort.GetPortNames().Length) 
      { 
       foreach (string s in SerialPort.GetPortNames()) 
       { 
        if (comboBox1.Items[i++].Equals(s) == false) 
        { 
         quantDiferente = true; 
        } 
       } 
      } 
      else 
      { 
       quantDiferente = true; 
      } 

      //it was't detected difference 
      if (quantDiferente == false) 
      { 
       return;      
      } 

      //clean comboBox 
      comboBox1.Items.Clear(); 

      //add all the COMs in the list 
      foreach (string s in SerialPort.GetPortNames()) 
      { 
       comboBox1.Items.Add(s); 
      } 
      //select the first position 
      comboBox1.SelectedIndex = 0; 
     } 

     private void timerCOM_Tick(object sender, EventArgs e) 
     { 
      atualizaListaCOMs(); 
     } 

     private void btConectar_Click(object sender, EventArgs e) 
     { 
      if (serialPort1.IsOpen == false) 
      { 
       try 
       { 
        serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString(); 
        serialPort1.Open(); 

       } 
       catch 
       { 
        return; 

       } 
       if (serialPort1.IsOpen) 
       { 
        btConectar.Text = "Desconectar"; 
        comboBox1.Enabled = false; 

       } 
      } 
      else 
      { 

       try 
       { 
        serialPort1.Close(); 
        comboBox1.Enabled = true; 
        btConectar.Text = "Conectar"; 
       } 
       catch 
       { 
        return; 
       } 

      } 
     } 

     private void Form1_FormClosed(object sender, FormClosedEventArgs e) 
     { 
      if(serialPort1.IsOpen == true) // if the port is open 
      serialPort1.Close();   //close 
     } 

     private void btEnviar_Click(object sender, EventArgs e) 
     { 
      if(serialPort1.IsOpen == true)   //porta está aberta 
      serialPort1.Write(textBoxX.Text); //send the text from textboxX 
      serialPort1.Write(textBoxY.Text); 
     } 

     private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) 
     { 
      RxString = serialPort1.ReadExisting();    //read data from serial 
      this.Invoke(new EventHandler(trataDadoRecebido)); 
     } 

     private void trataDadoRecebido(object sender, EventArgs e) 
     { 
      textBoxReceber.AppendText(RxString); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 
    } 
} 

Arduino的腳本

void setup() 
{ 
    Serial.begin(9600); 
} 


    void loop() 
    { 
     if(Serial.available())   
     { 
     char c = Serial.read(); 
     Serial.println(c);   
     } 
    } 

回答

2

通過串行端口和使用字符串分隔它們讀取數據。

在C#

  1. 添加獨特的個性來1箱數據的開始。
  2. 添加一個獨特的字符來開始第二個盒子數據。
  3. 添加一個獨特的字符結束第二個盒子數據。
  4. 附加兩個字符串並作爲單個字符串發送。

我有VB例如:

Dim WithEvents ADRport As SerialPort = New System.IO.Ports.SerialPort("COM1", 9600, Parity.None, 8, StopBits.One) 

msg = "$" & box1.Text & "#" & box2.Text & "*" & vbCrLf 
ADRport.Write(msg) 

在阿爾杜伊諾:

//--- Wait for the message starting ----- 
while(Serial.read()!='$'); 
while (!flag) 
{ 
// get the new byte: 
char inChar = (char)Serial.read(); 
// add it to the inputString: 
mstr += inChar; 
//Serial.write(inChar); 
// if the incoming character is a end of line, set a flag 
if (inChar == '*') 
{ 
    flag = true; 
} 
} 

單獨串使用

int 1start = int(mstr.indexOf('$')); 
int 2start = int(mstr.indexOf('#',numstart+1)); 
int 2end = int(mstr.indexOf('*')); 
text1 = mstr.substring(1start+1,2start); 
text2 = mstr.substring(2start+1,2end); 
text1.trim(); 
text1.trim(); 

然後顯示它ONN液晶/的serialport:

lcd.setCursor(0,0); 
lcd.print(msg); 

請注意'$'不會被添加到字符串中。

1

這就是我所做的,和它的工作:

C#

serialPort1.WriteLine(eixver.Text.ToString()+";"+ eixHor.Text.ToString()); 

的Arduino:

int val; 
int h, v; 


String cont; 
void setup() { 
Serial.begin(9600); 

} 

void loop() { 

while(Serial.available()) 
{ 
char caracter = Serial.read(); 
cont.concat(caracter); 
delay(5); 
} 
if(cont!="") 
{ 
// Serial.println(cont); 
v=cont.substring(0, cont.indexOf(';')).toInt(); 
h=cont.substring(cont.indexOf(';')+1, cont.length()).toInt(); 
Serial.print("v="); 
Serial.print(v); 
Serial.print(" - h="); 
Serial.print(h); 
cont=""; 
} 

} 
0

我認爲,這是對你有好處。 C#部分:

Connect(); 
    if (serialPort1.IsOpen) 
    { 

     double MyInt = ToDouble(lblMixerCase.Text); 
     byte[] b = GetBytes(MyInt); 
     serialPort1.Write(b, 0, 1); 

     double MyInt2 = ToDouble(txtRPM.Text); 
     byte[] z = GetBytes(MyInt2); 
     serialPort1.Write(z, 0, 1); 
     if (MyInt2>1600) 
     { 
      MessageBox.Show("Please enter RPM value between 0 and 1600"); 
     } 
     double MyInt3 = ToDouble(lblCaseRpmSecond.Text); 
     byte[] p = GetBytes(MyInt3); 
     serialPort1.Write(p, 0, 1); 

     double MyInt4 = ToDouble(lblRpmCaseThree.Text); 
     byte[] s = GetBytes(MyInt3); 
     serialPort1.Write(s, 0, 1); 

     serialPort1.Close(); 

Arduino的一部分:

unsigned long currentMillis = millis(); 
    if (currentMillis - previousMillis >= interval) { 
    previousMillis = currentMillis; 
    if (Serial.available() > 0) { 
     // read the incoming byte: 
     n = Serial.read(); 
     if (i < 3) 
     { 
     number[i] = n; 

     switch (number[0]) 
     { 
      case 1: 
      if (i == 2) 
      { 
       switch(number[1]) 
       { 
       case 1: 
       openClose(); 
       break; 
       case 2: 
       openCloseTwice(); 
       break; 
       case 3: 
       openCloseThree(); 
       break; 
       default: 
       openCloseIwanted(number[1], number[2]); 
       break; 
       } 
      } 
      break; 
      case 2: 
      if (i == 2) 
      { 
       switch(number[1]) 
       { 
       case 1: 
       openClose(); 
       break; 
       case 2: 
       openCloseTwice(); 
       break; 
       case 3: 
       openCloseThree(); 
       break; 
       default: 
       openCloseIwanted(number[1], number[2]); 
       break; 
       } 
      } 
      break; 
      case 3: 
      if (i == 2) 
      { 
       openCloseIwanted(number[1], number[2]); 
      } 
      break; 
      default: 
      if (i == 2) 
      { 
       openCloseIwanted(number[1], number[2]); 
      } 
      break; 
     } 
     i++; 
     if (i == 3) 
     { 
      asm volatile (" jmp 0"); //For reset Arduino 
     } 
     } 
     else 
     { 
     i = 0; 
     } 
    }