พอดีผมรับค่าจาก Serial Port จากฝั่ง Arduino แล้วเกิดปัญหา Convert ไม่ได้ครับ บางครั้งยอมให้รันโปรแกรมและแปลงได้ได้ บางครั้งไม่ยอมให้รันโปรแกรม เกิดจากสาเหตุอะไรครับ พอมีวิธีแก้ไหมครับ ขอบคุณครับ
Code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
Dim lists As String() = IO.Ports.SerialPort.GetPortNames
For i = 0 To lists.Count - 1
ComboBox1.Items.Add(lists(i))
Next
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim line As String
Dim sensor(6) As Integer
Dim myLabel = New Label(5) {Label0, Label1, Label2, Label3, Label4, Label5}
If SerialPort1.BytesToRead > 0 Then
line = SerialPort1.ReadLine
' Labeltest.Text = line
line = line.Trim
If line = "ARDUINO_SEND" Then
For i As Integer = 0 To 5
line = SerialPort1.ReadLine
line.Trim()
sensor(i) = Convert.ToInt32(line)
If sensor(i) > 25 Then
myLabel(i).Text = "ว่าง"
myLabel(i).ForeColor = Color.Green
Else
myLabel(i).Text = "ไม่ว่าง"
myLabel(i).ForeColor = Color.Red
End If
If sensor(0) > 25 Then
PictureBox1.ImageLocation = "C:\Users\Jame\Desktop\Project\pic\p1.png"
Else
PictureBox1.ImageLocation = "C:\Users\Jame\Desktop\Project\pic\p1car.png"
End If
' If sensor(1) > 25 Then
'PictureBox2.ImageLocation = "C:\Users\Jame\Desktop\Project\pic\p2.png"
'Else
'PictureBox2.ImageLocation = "C:\Users\Jame\Desktop\Project\pic\p2car.png"
'End If
Next
End If
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If SerialPort1.IsOpen Then SerialPort1.Close()
If Button1.Text = "Connect" Then
SerialPort1.BaudRate = 9600
SerialPort1.PortName = ComboBox1.SelectedItem
Try
Timer1.Enabled = True
Timer1.Interval = 1000
SerialPort1.Open()
Button1.Text = "Disconnect"
ComboBox1.Enabled = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
Button1.Text = "Connect"
ComboBox1.Enabled = True
End If
End Sub
End Class
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Try
Dim sp As SerialPort = CType(sender, SerialPort)
Dim RecievedData As String
RecievedData = sp.ReadExisting()
If Not(RecievedData = "") Then
Me.BeginInvoke(New LineReceivedEvent(AddressOf LineReceived), RecievedData)
End If
Catch __unusedException1__ As Exception
Console.WriteLine("Error !!!")
End Try
End Sub
Private Delegate Sub LineReceivedEvent(ByVal line As String)
Private Sub LineReceived(ByVal line As String)
MessageBox.Show(line)
Thread.Sleep(1000)
End Sub