使用VB.NET显示Arduino传感器值
问题描述:
我正在尝试创建一个应用程序来使用VB .NET显示来自Arduino的湿度传感器值。我想在Label1.Text中显示传感器值,但它似乎并不总是显示正确的值。使用VB.NET显示Arduino传感器值
我也尝试显示值到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
答
你为什么要使用Val
设置你Label1
的Text
财产?
Val
将包含在字符串中的数字作为数值返回,并停止在第一个字符处读取字符串,而无法将其识别为数字的一部分。
E.g:
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")
如果您收到的读值作为字符串...
Label1.Text = text
答
所以我发现我的问题的解决方案。我使用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
。
我试过这个,但仍然不起作用。我使用ReadLines()而不是ReadExisting(),做了很少的改变,现在我的问题解决了。不管怎么说,还是要谢谢你! – vj2daworld