我一直在嘗試使用COM串口檢索兩種不同秤的重量值。通過串口通過磅秤請求重量值
秤是CAS ER Plus和UWE AM-15K。
我已經設法創建了一個小程序來啓動PC和Scales之間的通信,但是我遇到了一個問題,我一直無法找到解決方案。
我可以發送ENQ命令,我收到ACK成功地從兩個尺度,但是當我發送DC1命令檢索的重量,我總是從信息獲取的各種變化
「十六進制數必須比7fffffffffffffff」
而且
「六角值必須是32個字符的最大長度。」
我的代碼來配置COM端口如下:
Try
comport.PortName = "COM1"
comport.BaudRate = 9600
comport.Parity = Parity.None
comport.DataBits = 8
comport.StopBits = StopBits.One
comport.Handshake = Handshake.XOnXOff
If DTRCheck.Checked Then
comport.DtrEnable = True
End If
If RTSCheck.Checked Then
comport.RtsEnable = True
End If
'Dim encoding As System.Text.Encoding = System.Text.Encoding.GetEncoding("IBM860")
Dim encoding As System.Text.Encoding = System.Text.Encoding.ASCII
comport.Encoding = encoding
comport.Open()
erroCOM = False
Catch ex As Exception
erroCOM = True
End Try
我的代碼發送命令:
If comport.IsOpen Then
TxtValor.Clear()
Try
If EnqComBtn.Checked Then 'Verify if the scale is "listening"
ListBox1.Items.Add("PC: ENQ - >")
comport.Write(New Byte() {&H5}, 0, 1)
Thread.Sleep(20)
ListBox1.Items.Add("PC: DC1 - >")
comport.Write(New Byte() {&H11}, 0, 1)
End If
If DC1ComBtn.Checked Then 'Request weight value
ListBox1.Items.Add("PC: DC1 - >")
comport.Write(New Byte() {&H11}, 0, 1)
Thread.Sleep(20)
End If
Catch ex As Exception
End Try
End If
發送的命令後,我有程序讀取值通過COM串行端口的DataReceived事件接收並將十六進制值轉換爲十進制。
編輯:
這是我用來讀取接收字節和字節將其轉換爲十六進制的代碼。我在StackOverflow的另一篇文章中發現了這段代碼,並編輯了空格部分。
私人小組comport_DataReceived(發送者爲對象,E作爲SerialDataReceivedEventArgs)處理comport.DataReceived
Dim RXByte As Byte
Do
RXCnt = 0
Do
RXByte = comport.ReadByte
RXArray(RXCnt) = LookUpTable(RXByte >> 4) ' Convert each byte to two hexadecimal characters
RXCnt = RXCnt + 1
RXArray(RXCnt) = LookUpTable(RXByte And 15)
RXCnt = RXCnt + 1
Loop Until (comport.BytesToRead = 0)
'----- End of communication protocol handling -------------------------------------------------------------
Me.Invoke(New MethodInvoker(AddressOf Display)) ' Start "Display" on the UI thread
Loop Until (comport.BytesToRead = 0) ' Don't return if more bytes have become available in the meantime
End Sub
有沒有人發現這個問題之前,如果是這樣,你有沒有發現一個解決方案? 謝謝!
您沒有發佈錯誤代碼。刪除Thread.Sleep()調用,以便不能忽略該錯誤。 –
問題是,只要我在COM端口寫入&H11,我立即在COMport上獲得15個字節。BytesToRead屬性並將其從十六進制轉換爲十二進制後,它將轉換爲「十六進制數字必須小於7fffffffffffffff」或「十六進制值必須是最大長度爲32個字符」。 – MetalHeadOwl