Arduino nano pc 串口通信

internetofthings 2020-01-29

上回书说到(以下省略100字)

说到底还是要自己写一个PC和Arduino 通信的程序,毕竟还是要集成到咱的系统上来。

c# 其实本身是有串口通信的类库的

arduino也自带软硬串行通信类库

两个类库一对话,一切就成了。

哦,我用的vb,哈哈哈

Imports System.IO.Ports

Public Class Form1
    Private WithEvents port As SerialPort
    Private Sub btnPort_Click(sender As Object, e As EventArgs) Handles btnPort.Click
        cbPort.Items.Clear()
        cbPort.Items.AddRange(SerialPort.GetPortNames())
        If cbPort.Items.Count Then
            cbPort.Text = cbPort.Items(0)
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        cbPort.Items.Clear()
        cbPort.Items.AddRange(SerialPort.GetPortNames())
        If cbPort.Items.Count Then
            cbPort.Text = cbPort.Items(0)
        End If
    End Sub

    Private Sub cbPort_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbPort.SelectedIndexChanged
        If cbPort.Text = "" Then Exit Sub
        If Not port Is Nothing Then
            If port.IsOpen Then
                port.Close()
            End If
            port.Dispose()
        End If
        port = New SerialPort(cbPort.Text, 9600, Parity.None, 8, StopBits.One)
        port.Open()
    End Sub
    Private Sub port_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles port.DataReceived
        If port.IsOpen Then
            Dim receiveData As String = port.ReadLine()
            Me.Invoke(Sub()
                          tbReceive.Text = tbReceive.Text + receiveData + vbCrLf
                      End Sub)
        End If
    End Sub

    Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
        If tbSend.Text = "" Then
            Exit Sub
        End If
        If port.IsOpen Then
            port.WriteLine(tbSend.Text)
        End If
    End Sub
End Class

相关推荐

TonyCode / 0评论 2012-02-05