我正在尝试创建一个应用程序,使用VB .NET显示来自Arduino的水分传感器值。我想在Label1.Text中显示传感器值,但似乎并不总是显示正确的值。
我还试图将值显示给RichTextBox,它可以显示正确的值。例如,如果读取值为1023,则RichTextBox1中显示的值为1023,但Label1中的值为23,或023,有时为3.
对此有何帮助?
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String)
If Me.RichTextBox1.InvokeRequired Then
Dim x As New SetTextCallBack(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
RichTextBox1.Text &= [text]
Label1.Text = Val([text])
End If
End Sub
答案 0 :(得分:1)
为什么使用Val
设置Text
的{{1}}属性?
Label1
将字符串中包含的数字作为数字值返回,并停止在第一个字符处读取字符串,该字符串无法识别为数字的一部分。
例如:
Val
如果您收到读取值为字符串...
Dim valResult As Double
' The following line of code sets valResult to 2457.
valResult = Val("2457")
' The following line of code sets valResult to 2457.
valResult = Val(" 2 45 7")
' The following line of code sets valResult to 24.
valResult = Val("24 and 57")
答案 1 :(得分:0)
所以我找到了解决问题的方法。我使用了ReadLine()而不是ReadExisting()并进行了一些字符串操作。
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
readbuffer = SerialPort1.ReadLine()
Me.Invoke(New EventHandler(AddressOf ReceivedText))
End Sub
Public Sub ReceivedText(ByVal sender As Object, ByVal e As System.EventArgs)
Dim read As Decimal
read = readbuffer.Replace(vbCr, "").Replace(vbLf, "")
Label1.Text = read
End Sub