如何将数据阵列从Arduino发送到vb

时间:2013-09-11 20:45:43

标签: vb.net serial-port arduino

我正在尝试将数据字节从Arduino发送到我的visual basic app,但它不起作用。我已经尝试了几种解决方案,但我没有得到这些值,我已发送给arduino。

我用于visual basic app的代码:

    Private Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)

    Dim bytes As Integer = 6
    Dim comBuffer As Byte() = New Byte(bytes - 1) {}
    'read the data and store it
    SerialPort1.Read(comBuffer, 0, bytes)
    Dim aryReceived(10) As Integer
    For i As Integer = 1 To (bytes - 1)
        aryReceived(i) = comBuffer(i)
        Y(i) = aryReceived(i)
    Next

    a = comBuffer(1)
    b = comBuffer(2)

End Sub

Private Sub Verzenden()

    Dim waardes() As Byte
    waardes = {X(1), X(2), X(3), X(4), X(5), X(6)}

    If SerialPort1.IsOpen = True Then

        SerialPort1.Write(waardes, 0, waardes.Length)

    End If

End Sub

Private Sub VerzendButton_Click(sender As Object, e As EventArgs) Handles VerzendButton.Click

    X(1) = 10
    X(2) = 11
    X(3) = 12
    X(4) = 13
    X(5) = 14
    X(6) = 15
    Verzenden()

End Sub

和arduino代码:

int x[9];

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

void loop() {
  if(Serial.available() >= 6){
    for(int i = 1; i < 7; i++){
      x[i] = Serial.read();
    }
    for(int i = 1; i < 7; i++){
      Serial.println(x[i]);
    }
  }
}

我向arduino发送6个字节,其值如下:10,11,12,13,14&amp; 15,但有时我必须在调试器中断之前发送两次字节。在&amp;中返回的值b与我发送的不一样。发送字节的代码工作正常。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我设置的断点位于receive事件的'end sub'命令。我经常得到51和b 56,但在其他时候它们是随机的。

X,Y和a&amp; b都是公开定义的。

Public Class Form1
    Dim indata As Integer

    Dim Setting As New My.MySettings()
    Dim Opstartmodus As Byte
    Dim OpstartCOMpoort As String

    Dim myPort As Array
    Delegate Sub SetTextCallBack(ByVal [text] As String)

    Dim a As Byte, b As Byte, c As Byte, d As Byte, f As Byte, g As Byte

    Dim WaardeVerzenden As Byte, X(9) As Byte, Y(9) As Byte

编辑:我在接收动作和sens动作之间的arduino代码中添加了500微秒的延迟。现在,单击发送按钮后,调试器立即中断。这个问题解决了!但现在,我总是得到以下啪啪声:49,48,13,10,49,49。这完全与我发送给Arduino的模式不匹配:(

答案 1 :(得分:0)

我找到了解决方案;)我将Serial.println替换为Serial.write(x,6)。在Visual Basic应用程序中,我将以下事件替换为:

Private Sub SerialPort1_DataReceived(sender As Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

            For i As Integer = 0 To (Bytes - 1)
                Y(i) = SerialPort1.ReadByte()
            Next
End Sub

Visual Basic应用程序现在接收我从arduino发送的数据:)