串口通信如何发送和接收数据

richardvip 2008-06-24 03:48:13
我是新手,先做一个串口通信的简单软件,还望大家帮助,如果能有例子最好,谢谢
...全文
1088 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
aiguoa3 2008-06-26
  • 打赏
  • 举报
回复
Imports System.IO.Ports
Dim rs232 As SerialPort
rs232 = New SerialPort(Combo.SelectedItem.ToString, 9600, Parity.None, 8, StopBits.One)
If Not rs232.IsOpen Then
Try
rs232.Open()

Catch ex As Exception
MsgBox("不打开")
End Try

If rs232.IsOpen Then MsgBox("open")
Else
MsgBox("不能打开")
End If
gsmsdn 2008-06-26
  • 打赏
  • 举报
回复
最近在做串口通讯项目,这是我自己写的基础的收和发,参考下吧:

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
slpCom.open()
If txtSendData.Text = "" Then
Exit Sub
End If
If slpCom.IsOpen = True Then
slpCom.WriteLine(txtSendData.Text)
Else
MsgBox("打开串口")
End If

slpCom.close()
End Sub


Private Sub slpCom_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles slpCom.DataReceived
Dim readBuffer(4096) As Byte
Dim intLength As Integer = slpCom.Read(readBuffer, 0, 4096)
Dim bteData(intLength - 1) As Byte
Array.Copy(readBuffer, 0, bteData, 0, intLength - 1)
Me.Invoke(interfaceUpdateHandle, bteData)
End Sub

interfaceUpdateHandle 是个委托,这里你可以自己写想要的方法,
bteData就是接受到的字节流
gh_li 2008-06-25
  • 打赏
  • 举报
回复
路过,学习
yj7416 2008-06-25
  • 打赏
  • 举报
回复
Private Sub Command1_Click()

'定义所要发送的数据
Dim bytebuf(1 To 12) As Byte
bytebuf(1) = &H55
bytebuf(2) = &H54
bytebuf(3) = &H0
bytebuf(4) = &H0
bytebuf(5) = &H0
bytebuf(6) = &H0
bytebuf(7) = &H0
bytebuf(8) = &H0
bytebuf(9) = &H0
bytebuf(10) = &H0
bytebuf(11) = &HAC
bytebuf(12) = &HFE

'发送数据
MSComm1.Output = bytebuf
'Debug.Print bytebuf(1)


End Sub


Private Sub Form_Load()
MSComm1.Settings = "115200,N,8,1" '设置串口参数
MSComm1.CommPort = 1 '选择串口1
MSComm1.InputMode = comInputModeBinary '设置接收模式为二进制
MSComm1.RThreshold = 1
MSComm1.PortOpen = True '打开串口
MSComm1.InBufferCount = 0 '清空发送缓冲区
End Sub

Private Sub MSComm1_OnComm()
Dim i%
Dim inbyte() As Byte
Select Case MSComm1.CommEvent
Case comEvCD
Case comEvCTS
Case comEvDSR
Case comEvRing
Case comEvReceive
'接收事件
Buf = ""
MSComm1.InputLen = 0 'read all input buffer
inbyte = MSComm1.Input '接受数据,接收的数据在mscomm1.input中

'这里根据你的数据格式自己设定
For i = LBound(inbyte) To UBound(inbyte)
Buf = Buf + Hex(inbyte(i))
Next i

Label1.Caption = Buf
Case comEvSend
End Select


End Sub
cl9876 2008-06-24
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20080619/08/DCEF3FE2-F95B-4918-8EDB-36D48A3D0528.html
这上头的资料很全
niewb 2008-06-24
  • 打赏
  • 举报
回复

Dim com As New System.IO.Ports.SerialPort(Me.components)
Dim s() As Byte = {&HAA, &H11, &HFE, &H1, &H1, &H11}
com.Open()
com.Write(s, 0, s.Length)
com.Close()

16,722

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧