Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Imports System.IO
Public Class Form1
'------------------------------------------------
Dim myPort As Array
Dim filePath As String
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
'------------------------------------------------
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.PortName = "COM1"
SerialPort1.BaudRate = "9600"
SerialPort1.Open()
'myPort = IO.Ports.SerialPort.GetPortNames()
'ComboBox1.Items.AddRange(myPort)
Timer1.Enabled = True
Timer1.Interval = 1000
Dim Weight As String = RichTextBox2.Text.Length()
TextBox1.Text = Weight
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
SerialPort1.Write(RichTextBox2.Text & vbCr) 'concatenate with \n
'SaveTextToFile(RichTextBox2.Text, "D:\weight.txt")
filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "weight.txt")
My.Computer.FileSystem.WriteAllText(filePath, RichTextBox2.Text, False)
Dim Weight As String = RichTextBox2.Text.Length()
If Weight > 400 Then
RichTextBox2.Text = ""
End If
End Sub
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) 'input from ReadExisting
If Me.RichTextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.RichTextBox2.Text &= [text] 'append text
End If
End Sub
Public Function SaveTextToFile(ByVal strData As String, _
ByVal FullPath As String, _
Optional ByVal ErrInfo As String = "") As Boolean
'Dim Contents As String
Dim bAns As Boolean = False
Dim objReader As StreamWriter
Try
objReader = New StreamWriter(FullPath)
objReader.Write(strData)
objReader.Close()
bAns = True
Catch Ex As Exception
ErrInfo = Ex.Message
End Try
Return bAns
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Timer1.Stop()
Timer1.Enabled = False
If SerialPort1.IsOpen Then
SerialPort1.Close()
End If
Application.Exit()
End Sub
End Class