?? mainform.vb
字號:
Option Explicit On
Option Strict On
Imports System.IO.Ports
Imports System.Text
Public Class MainForm
' Demonstrates communications between a USBwiz-OEM board and a USB flash drive
' attached to the USBwiz-OEM.
' The Visual-Basic application functions as host software that sends commands
' to the host controller in the USBwiz.
' Why use a PC to control the USB host controller on the USBwiz-OEM?
' The PC interface makes it easy to experiment with the code.
' When the code is working, you can port it to any microcontroller with a UART port.
' I used a DLP Electronics DLP-USB232M module to interface the USBwiz's asynchronous serial
' port to a USB port on a PC. You can instead use a MAX233 or similar chip to connect the
' USBwiz to an RS-232 port or a USB/RS-232 converter on a PC.
' Connections:
' USBwiz-OEM DLP-USB232M
' 1-----------23
' 2-----------24
' 6-----------21
' 7-----------22
' USBwiz-OEM
' Connect pins 13, 14, 17, 18 to +5V.
' Connect pins 15, 16 to GND.
' DLP-USB232M
' Connect pins 3, 10, 11, 14 to +5V.
' Connect pins 2, 5, 7, 19 to GND.
' Use a regulated +5V supply.
' Attach a flash drive to the bottom USB connector on the USBwix-OEM.
' For more about the USBwiz, go to ghielectronics.com.
' For more about USB and mass storage, go to Lvr.com.
' Send error reports, comments, etc. to jan@Lvr.com
' By Jan Axelson
' Version 0.9
Friend enumerated As Boolean
Friend portChange As Boolean
Friend previousPortIndex As Integer
Friend receiveBuffer As String
Friend selectedPort As New System.IO.Ports.SerialPort
Friend selectedPortIndex As Integer
Dim previousTime As Date
Dim timeOfTransfer As String
Dim transferInProgress As Boolean
'******************************************************************************************
' Variables used in USBwiz commands.
' See the USBwiz manual for more info.
Dim deviceHandle As String = "0"
Dim fileHandle As String = "0" ' Valid values: 0, 1, 2, 3.
Dim fileName As String = "test.txt" ' The file to write to and read.
Dim fileSystem As String = "0" ' Valid values: 0, 1, 2.
' Used by the RF command if the file being read is shorter than the requested data.
Dim fillerSymbol As String = " "
Dim lun As String = "0" ' Many drives have only LUN 0.
Dim massStorageHandle As String = "0"
Dim usbPort As String = "0" ' Port 0 is the bottom connector on the USBwiz-OEM board.
'******************************************************************************************
' USBwiz success code.
Const Success As String = "!00"
'Used in error messages.
Const ModuleName As String = "USBwiz Demo"
Private Sub btnEnumerateDrive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnumerateDrive.Click
' Enumerate the drive and assign handles.
InitializeDriveCommunications()
End Sub
Private Sub btnReadFromFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadFromFile.Click
' Read from a file on the flash drive.
ReadFromFile()
End Sub
Private Sub btnWriteToFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnWriteToFile.Click
'Write to a file on the flash drive.
WriteToFile()
End Sub
Private Sub CloseComPort()
If (Not IsNothing(selectedPort)) Then
If selectedPort.IsOpen Then
selectedPort.Dispose()
End If
End If
End Sub
Private Sub CloseDeviceHandle()
' Purpose : close the device handle.
' The application will need to re-enumerate the device to resume communicating.
Dim command As String
Dim response As String
txtMonitor.AppendText("Closing the device handle." + vbCrLf)
If Enumerated Then
command = "UR " + deviceHandle
response = SendCommandToUsbwiz(command)
End If
enumerated = False
transferInProgress = False
End Sub
Private Function DisplayDateAndTime() As String
' Purpose : get and format the current date and time.
' Returns : the data and time.
Dim DateAndTime As Date = DateTime.Now
Dim DateAndTimeString As String = ""
DateAndTimeString = DateAndTime.ToString("G")
Return DateAndTimeString
End Function
Private Sub DisplayFailureMessage(ByVal command As String, ByVal response As String)
' Purpose : display a failure message in a text box.
' Accepts : command - the command that failed
' response - the response code
txtMonitor.AppendText _
("Failed executing command " + command + " with response = " + response + "." + vbCrLf)
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Show()
MyMainForm = Me
MyPortSettings = New PortSettings
transferInProgress = False
InitializeDisplayElements()
MyPortSettings.InitializePortSettings()
End Sub
Private Function ReadFileContents(ByRef receivedData As String, ByRef bytesRead As Integer, ByVal bytesToRead As Integer) As String
' Purpose : Gets the requested number of bytes from the receive buffer.
' Accepts : receivedData - a string to hold the received bytes.
' bytesRead - the number of bytes returned.
' bytesToRead - the number of bytes requested.
' Returns : USBwiz response code
Dim byteBuffer() As Byte
Dim incomingData As String = ""
Dim newData As String = ""
Dim response As String = ""
Dim totalBytesRead As Integer
' Set the size of the buffer to match the number of bytes to read.
ReDim byteBuffer(bytesToRead - 1)
Do
' Read the port until we have the requested number of bytes or a timeout.
bytesRead = selectedPort.Read(byteBuffer, 0, bytesToRead - totalBytesRead)
' Keep track of how many bytes have been read.
totalBytesRead = totalBytesRead + bytesRead
' Save the data read as a string.
newData = Encoding.Default.GetString(byteBuffer, 0, bytesRead)
' Append the new data to any previously read data.
receivedData = receivedData + newData
Loop Until (totalBytesRead >= bytesToRead)
'The USBwiz follows the requested data with the number of valid bytes returned.
response = ReadDataFromUsbwiz(CStr(bytesRead))
Return response
End Function
Private Sub InitializeDisplayElements()
' Purpose : initialize elements on the main form.
' Textbox elements:
txtMonitor.Multiline = True
txtMonitor.ScrollBars = ScrollBars.Vertical
txtMonitor.AcceptsReturn = True
txtMonitor.AcceptsTab = True
txtMonitor.WordWrap = True
txtMonitor.Multiline = True
End Sub
Private Sub InitializeDriveCommunications()
' Purpose : Send commands to the USBwiz to enumerate a drive and mount a file system.
Dim command As String = ""
Dim freeMedia As String = ""
Dim response As String = ""
Dim maxLun As String = ""
Dim mediaSize As String = ""
Dim mediaStatistics As String = ""
Dim stringIndex As Integer
Try
transferInProgress = True
txtMonitor.Clear()
' Open the COM port if necessary.
If portChange Then
' The user has changed the selected COM port.
portChange = False
' If a previously opened port is open, close it.
CloseComPort()
' Open the new selected port.
OpenComPort()
Else
If Not (IsNothing(selectedPort)) Then
If Not (selectedPort.IsOpen) Then
' A port has been initialized but the port isn't open.
OpenComPort()
End If
Else
' A port hasn't been initialized or opened.
OpenComPort()
End If
End If
enumerated = False
' Close the device handle if one was open.
' Returns success even if no handle was open.
command = "UR " + deviceHandle
response = SendCommandToUsbwiz(command)
If (Not IsNothing(selectedPort)) Then
If selectedPort.IsOpen Then
' The port exists and is open.
command = "UI " + usbPort + ">" + deviceHandle
txtMonitor.AppendText _
("Enumerating and assigning a device handle to the USB drive: " + command + vbCrLf)
response = SendCommandToUsbwiz(command)
If (response = Success) Then
command = "UM " + deviceHandle + ">" + massStorageHandle
txtMonitor.AppendText _
("Registering the drive's device handle to a mass-storage handle: " + command + vbCrLf)
response = SendCommandToUsbwiz(command)
If (response = Success) Then
response = ReadDataFromUsbwiz(maxLun)
txtMonitor.AppendText("Max LUN = " + maxLun.Trim("$"c) + vbCrLf)
If (response = Success) Then
command = "AM U" + massStorageHandle + "<" + lun
txtMonitor.AppendText _
("Attaching to a LUN of the USB drive: " + command + vbCrLf)
response = SendCommandToUsbwiz(command)
If (response = Success) Then
command = "MU " + fileSystem + ">U" + massStorageHandle
txtMonitor.AppendText _
("Mounting a file system on the mass-storage handle: " + command + vbCrLf)
response = SendCommandToUsbwiz(command)
If (response = Success) Then
enumerated = True
txtMonitor.AppendText _
("Ready to communicate with the drive." + vbCrLf)
command = "MS"
txtMonitor.AppendText _
("Requesting media statistics: " + command + vbCrLf)
response = SendCommandToUsbwiz(command)
response = ReadDataFromUsbwiz(mediaStatistics)
' Remove the first "$" in the response.
mediaStatistics = mediaStatistics.Trim("$"c)
' Get the location of the second "$".
stringIndex = mediaStatistics.IndexOf("$"c)
' Media size is everything up to the second "$".
mediaSize = mediaStatistics.Substring(0, stringIndex - 1)
txtMonitor.AppendText("Media size = " + CStr(Convert.ToInt32(mediaSize, 16)) + " bytes." + vbCrLf)
' Free media is what follows the second "$".
freeMedia = mediaStatistics.Trim("$"c)
freeMedia = mediaStatistics.Substring(stringIndex + 1, 8)
txtMonitor.AppendText("Free media = " + CStr(Convert.ToInt32(freeMedia, 16)) + " bytes." + vbCrLf)
Else
DisplayFailureMessage(command, response)
End If
Else
DisplayFailureMessage(command, response)
End If
Else
DisplayFailureMessage(command, response)
End If
Else
DisplayFailureMessage(command, response)
End If
Else
DisplayFailureMessage(command, response)
End If
Else
txtMonitor.AppendText("Unable to open the COM port.")
End If
Else
txtMonitor.AppendText("The selected COM port doesn't exist.")
End If
Catch ex As TimeoutException
txtMonitor.AppendText("Timeout" + vbCrLf)
CloseDeviceHandle()
Catch ex As InvalidOperationException
txtMonitor.AppendText("Invalid operation" + vbCrLf)
CloseDeviceHandle()
Finally
transferInProgress = False
End Try
End Sub
Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
CloseDeviceHandle()
CloseComPort()
End Sub
Private Sub OpenComPort()
' Purpose : open a COM port for communicating.
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -