1

我正在尝试将数据字节从 Arduino 发送到我的 Visual Basic 应用程序,但它不起作用。我已经尝试了几种解决方案,但我没有取回值,我已经发送到 arduino。

我用于 Visual Basic 应用程序的代码:

    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 和 15,但有时我必须在调试器中断之前发送两次字节。在 a & b 中返回的值与我发送的不同。发送字节的代码工作正常。

有人能帮我吗?

4

2 回答 2

0

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

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 发送的数据:)

于 2013-09-17T15:33:58.437 回答
0

我设置的断点位于接收事件的“结束子”命令处。我经常得到 51 和 b 56,但在其他时候它们是随机的。

X、Y 和 a & 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

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

于 2013-09-12T17:48:48.903 回答