Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
System.Windows.Forms.Control.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
Code
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedItem = "" Then Return
If SerialPort1.IsOpen Then SerialPort1.Close()
If Button1.Text = "Connect" Then
SerialPort1.BaudRate = 9600
SerialPort1.PortName = ComboBox1.SelectedItem
Try
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
Code
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim line As String = SerialPort1.ReadLine()
Label1.Text = line
End Sub
อันนี้ส่วน Code ฝั่ง Arduino ครับ Code
int pingPin = 13;
int inPin = 12;
void setup() {
Serial.begin(9600);
}
void loop()
{
long duration, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(inPin, INPUT);
duration = pulseIn(inPin, HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(50);
}
long microsecondsToCentimeters(long microseconds)
{
}
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'ใช้ตัวแปร line ในการตรวจสอบสถานะ
Dim line As String = SerialPort1.ReadLine()
Label1.Text = line
'ค่าที่รับมาจาก ReadLine() เป็น string ต้องนำส่วนตัวเลขแปลงเป็น integer ก่อน เพื่อนำไปคำนวณได้
Dim i As Integer = Convert.toInt32(line.Substring(0, line.Length - 2))
'ระยะการจอด
Dim check As Integer = 50
If i < check Then
'สมมติรูป P1 อยู่ใน PictureBox1
'กำหนดรูปเมื่อมีรถจอด
PictureBox1.Image = Image.FromFile("c:\Image\parked.jpg")
Else
'กำหนดรูปเมื่อยังไม่จอด
PictureBox1.Image = Image.FromFile("c:\Image\empty.jpg")
End If
End Sub