cara mengakses Port Paralel menggunakan Microsoft Visual Basic .NET

cara mengakses Port Paralel menggunakan Microsoft
Visual Basic .NET

Artikel ini selangkah demi selangkah menjelaskan cara mengakses port serial dan cara mengakses Port Paralel menggunakan Microsoft Visual Basic .NET. Artikel ini juga berisi kode contoh yang menunjukkan konsep yang dibahas dalam artikel ini.
Persyaratan
Daftar berikut ini mencantumkan perangkat keras yang disarankan, perangkat lunak, jaringan infrastruktur, dan paket layanan yang Anda butuhkan:
• Microsoft Windows Server 2003, Microsoft Windows XP, atau Microsoft Windows 2000
• Visual Basic .NET
Artikel ini mengasumsikan bahwa Anda sudah terbiasa dengan topik berikut ini:
• Pemrograman Visual Basic .NET
• Platform memanggil layanan Visual Basic .NET
Persyaratan
Karena Microsoft .NET Framework kelas tidak ada untuk mengakses sumber daya komunikasi yang tersambung ke komputer Anda, Anda dapat menggunakan kontrol MSComm di Microsoft Visual Basic 6.0. Kontrol MSComm menyediakan komunikasi serial untuk aplikasi Anda dengan mengaktifkan transmisi dan penerimaan data melalui serial port. Untuk menerapkan dasar komunikasi serial menggunakan modem, ikuti langkah-langkah berikut:
1. Mulai Microsoft Visual Studio .NET.
2. Pada File menu, arahkan ke baru, dan kemudian klik Project.
3. Pada Jenis proyek, klik Proyek Visual Basic.
4. Pada pola dasar, klik Aplikasi konsol.
5. Di kotak nama , ketik MyConsoleApplication, dan kemudian klik OK.

Secara default, Module1.vb dibuat.
6. Klik kanan MyConsoleApplication proyek, dan kemudian klik Menambahkan referensi.
7. Klik COM tab, klik Microsoft Comm kontrol 6.0 Komponennama, klik pilih, dan kemudian klik OK.

Catatan Untuk menggunakan kontrol MSComm , Anda harus menginstal komponen COM terkait Microsoft Visual Basic 6.0 pada komputer yang sama yang memiliki Microsoft Visual Studio .NET diinstal.

Untuk informasi selengkapnya tentang lisensi masalah ketika Anda menggunakan kontrol Visual Basic 6.0 di Visual Studio .NET, klik nomor artikel berikut ini untuk melihat artikel di Pangkalan Pengetahuan Microsoft:
318597 Galat saat Anda menggunakan kontrol Visual Basic 6.0 di Visual Studio .NET
8. Ganti kode di Module1.vb dengan contoh kode berikut.
9. Imports MSCommLib
10.
11. Module Module1
12.
13. Sub Main()
14. ‘New a MSComm control
15. Dim MSComm1 As MSComm
16. MSComm1 = New MSComm
17. ‘ Buffer to hold input string.
18. Dim Buffer As String
19. ‘ Use the COM1 serial port.
20. MSComm1.CommPort = 1
21. ‘ 9600 baud, no parity, 8 data, and 1 stop bit.
22. MSComm1.Settings = “9600,N,8,1”
23. ‘ Tell the control to read the whole buffer when Input is used.
24. MSComm1.InputLen = 0
25. ‘ Open the serial port.
26. MSComm1.PortOpen = True
27. Console.WriteLine(“Open the serial port.”)
28. ‘ Tell the control to make the Input property return text data.
29. MSComm1.InputMode() = InputModeConstants.comInputModeText
30. ‘Clear the receive buffer.
31. MSComm1.InBufferCount() = 0
32. ‘ Send the attention command to the modem.
33. MSComm1.Output = “ATV1Q0” & Chr(13)
34. Console.WriteLine(“Send the attention command to the modem.”)
35. Console.WriteLine(“Wait for the data to come back to the serial port…”)
36. ‘ Make sure that the modem responds with “OK”.
37. ‘ Wait for the data to come back to the serial port.
38. Do
39. Buffer = Buffer & MSComm1.Input
40. Loop Until InStr(Buffer, “OK” & vbCrLf)
41. ‘ Read the “OK” response data in the serial port.
42. ‘ Close the serial port.
43. Console.WriteLine(“Read the OK response data in the serial port.”)
44. MSComm1.PortOpen = False
45. Console.WriteLine(“Close the serial port.”)
46. End Sub
47.
End Module
48. Tekan CRTL + F5 untuk membuat dan menjalankan proyek ini. Anda akan menerima pesan output berikut ini:
Buka serial port.
Mengirim perintah perhatian ke modem.
Menunggu untuk data untuk kembali ke serial port…
Membaca data OK respons di serial port.
Tutup serial port.
Menggunakan kontrol MSComm dalam Visual Basic .NET untuk mengakses Porta serial
Untuk melakukannya, ikuti langkah-langkah berikut:
1. Mulai Microsoft Visual Studio .NET.
2. Pada File menu, arahkan ke baru, dan kemudian klik Project.
3. Pada Jenis proyek, klik Proyek Visual Basic.
4. Pada pola dasar, klik Aplikasi konsol.
5. Di kotak teks nama , ketik MyConsoleApplication, dan kemudian klik OK.

Secara default, Module1.vb dibuat.
6. Menambahkan kode berikut ke Module1.vb sebelum pernyataan Module1 modul :
7. Option Strict On
8.
9. ‘ Define a CommException class that inherits from the ApplicationException class,
10. ‘ and then throw an object of type CommException when you receive an error message.
11. Class CommException
12. Inherits ApplicationException
13. Sub New(ByVal Reason As String)
14. MyBase.New(Reason)
15. End Sub
End Class
16. Menyatakan struktur, konstanta dan referensi eksternal fungsi yang ada di Kernel32.dll

Memanggil fungsi yang tidak dikelola dari aplikasi Visual Basic .NET Anda berhasil, Anda harus menyatakan referensi ke struktur yang Anda berikan sebagai parameter fungsi tidak dikelola, dan Anda harus menyatakan konstanta yang Anda berikan sebagai parameter fungsi tidak dikelola. Untuk melakukannya, tambahkan kode berikut ke Module1.vb setelah pernyataan Module1 modul :
17. ‘Declare structures.
18. Public Structure DCB
19. Public DCBlength As Int32
20. Public BaudRate As Int32
21. Public fBitFields As Int32 ‘See Comments in Win32API.Txt
22. Public wReserved As Int16
23. Public XonLim As Int16
24. Public XoffLim As Int16
25. Public ByteSize As Byte
26. Public Parity As Byte
27. Public StopBits As Byte
28. Public XonChar As Byte
29. Public XoffChar As Byte
30. Public ErrorChar As Byte
31. Public EofChar As Byte
32. Public EvtChar As Byte
33. Public wReserved1 As Int16 ‘Reserved; Do Not Use
34. End Structure
35.
36. Public Structure COMMTIMEOUTS
37. Public ReadIntervalTimeout As Int32
38. Public ReadTotalTimeoutMultiplier As Int32
39. Public ReadTotalTimeoutConstant As Int32
40. Public WriteTotalTimeoutMultiplier As Int32
41. Public WriteTotalTimeoutConstant As Int32
42. End Structure
43.
44. ‘Declare constants.
45. Public Const GENERIC_READ As Int32 = &H80000000
46. Public Const GENERIC_WRITE As Int32 = &H40000000
47. Public Const OPEN_EXISTING As Int32 = 3
48. Public Const FILE_ATTRIBUTE_NORMAL As Int32 = &H80
49. Public Const NOPARITY As Int32 = 0
50. Public Const ONESTOPBIT As Int32 = 0
51.
52. ‘Declare references to external functions.
53. Public Declare Auto Function CreateFile Lib “kernel32.dll” _
54. (ByVal lpFileName As String, ByVal dwDesiredAccess As Int32, _
55. ByVal dwShareMode As Int32, ByVal lpSecurityAttributes As IntPtr, _
56. ByVal dwCreationDisposition As Int32, ByVal dwFlagsAndAttributes As Int32, _
57. ByVal hTemplateFile As IntPtr) As IntPtr
58.
59. Public Declare Auto Function GetCommState Lib “kernel32.dll” (ByVal nCid As IntPtr, _
60. ByRef lpDCB As DCB) As Boolean
61.
62. Public Declare Auto Function SetCommState Lib “kernel32.dll” (ByVal nCid As IntPtr, _
63. ByRef lpDCB As DCB) As Boolean
64.
65. Public Declare Auto Function GetCommTimeouts Lib “kernel32.dll” (ByVal hFile As IntPtr, _
66. ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
67.
68. Public Declare Auto Function SetCommTimeouts Lib “kernel32.dll” (ByVal hFile As IntPtr, _
69. ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
70.
71. Public Declare Auto Function WriteFile Lib “kernel32.dll” (ByVal hFile As IntPtr, _
72. ByVal lpBuffer As Byte(), ByVal nNumberOfBytesToWrite As Int32, _
73. ByRef lpNumberOfBytesWritten As Int32, ByVal lpOverlapped As IntPtr) As Boolean
74.
75. Public Declare Auto Function ReadFile Lib “kernel32.dll” (ByVal hFile As IntPtr, _
76. ByVal lpBuffer As Byte(), ByVal nNumberOfBytesToRead As Int32, _
77. ByRef lpNumberOfBytesRead As Int32, ByVal lpOverlapped As IntPtr) As Boolean
78.
Public Declare Auto Function CloseHandle Lib “kernel32.dll” (ByVal hObject As IntPtr) As Boolean
79. Sebelum Anda dapat mengakses serial port atau port paralel, Anda harus mendapatkan handle ke port yang sesuai dan kemudian mengkonfigurasi port komunikasi. Untuk melakukannya, tambahkan kode inisialisasi berikut untuk Module1.vb setelah pernyataan Sub utama .

Catatan Untuk membuat komunikasi dengan LPTx port, Anda harus menghentikan layanan Print Spooler. Untuk melakukannya, gunakan alat layanan di Alat administratif.
80. ‘ Declare the local variables that you will use in the code.
81. Dim hSerialPort, hParallelPort As IntPtr
82. Dim Success As Boolean
83. Dim MyDCB As DCB
84. Dim MyCommTimeouts As COMMTIMEOUTS
85. Dim BytesWritten, BytesRead As Int32
86. Dim Buffer() As Byte
87.
88. ‘ Declare the variables to use for encoding.
89. Dim oEncoder As New System.Text.ASCIIEncoding
90. Dim oEnc As System.Text.Encoding = oEncoder.GetEncoding(1252)
91.
92. ‘ Convert String to Byte().
93. Buffer = oEnc.GetBytes(“Test”)
94. Try
95. ‘ Access the serial port.
96. Console.WriteLine(“Accessing the COM1 serial port”)
97. ‘ Obtain a handle to the COM1 serial port.
98. hSerialPort = CreateFile(“COM1”, GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _
99. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)
100. ‘ Verify that the obtained handle is valid.
101. If hSerialPort.ToInt32 = -1 Then
102. Throw New CommException(“Unable to obtain a handle to the COM1 port”)
103. End If
104. ‘ Retrieve the current control settings.
105. Success = GetCommState(hSerialPort, MyDCB)
106. If Success = False Then
107. Throw New CommException(“Unable to retrieve the current control settings”)
108. End If
109. ‘ Modify the properties of the retrieved DCB structure as appropriate.
110. ‘ WARNING: Make sure to modify the properties according to their supported values.
111. MyDCB.BaudRate = 9600
112. MyDCB.ByteSize = 8
113. MyDCB.Parity = NOPARITY
114. MyDCB.StopBits = ONESTOPBIT
115. ‘ Reconfigure COM1 based on the properties of the modified DCB structure.
116. Success = SetCommState(hSerialPort, MyDCB)
117. If Success = False Then
118. Throw New CommException(“Unable to reconfigure COM1”)
119. End If
120. ‘ Retrieve the current time-out settings.
121. Success = GetCommTimeouts(hSerialPort, MyCommTimeouts)
122. If Success = False Then
123. Throw New CommException(“Unable to retrieve current time-out settings”)
124. End If
125. ‘ Modify the properties of the retrieved COMMTIMEOUTS structure as appropriate.
126. ‘ WARNING: Make sure to modify the properties according to their supported values.
127. MyCommTimeouts.ReadIntervalTimeout = 0
128. MyCommTimeouts.ReadTotalTimeoutConstant = 0
129. MyCommTimeouts.ReadTotalTimeoutMultiplier = 0
130. MyCommTimeouts.WriteTotalTimeoutConstant = 0
131. MyCommTimeouts.WriteTotalTimeoutMultiplier = 0
132. ‘ Reconfigure the time-out settings, based on the properties of the modified COMMTIMEOUTS structure.
133. Success = SetCommTimeouts(hSerialPort, MyCommTimeouts)
134. If Success = False Then
135. Throw New CommException(“Unable to reconfigure the time-out settings”)
136. End If
137. ‘ Write data to COM1.
138. Console.WriteLine(“Writing the following data to COM1: Test”)
139. Success = WriteFile(hSerialPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero)
140. If Success = False Then
141. Throw New CommException(“Unable to write to COM1”)
142. End If
143. ‘ Read data from COM1.
144. Success = ReadFile(hSerialPort, Buffer, BytesWritten, BytesRead, IntPtr.Zero)
145. If Success = False Then
146. Throw New CommException(“Unable to read from COM1”)
147. End If
148. Catch ex As Exception
149. Console.WriteLine(Ex.Message)
150. Finally
151. ‘ Release the handle to COM1.
152. Success = CloseHandle(hSerialPort)
153. If Success = False Then
154. Console.WriteLine(“Unable to release handle to COM1”)
155. End If
156. End Try
157.
158. Try
159. ‘ Parallel port.
160. Console.WriteLine(“Accessing the LPT1 parallel port”)
161. ‘ Obtain a handle to the LPT1 parallel port.
162. hParallelPort = CreateFile(“LPT1”, GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _
163. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)
164. ‘ Verify that the obtained handle is valid.
165. If hParallelPort.ToInt32 = -1 Then
166. Throw New CommException(“Unable to obtain a handle to the LPT1 port”)
167. End If
168. ‘ Retrieve the current control settings.
169. Success = GetCommState(hParallelPort, MyDCB)
170. If Success = False Then
171. Throw New CommException(“Unable to retrieve the current control settings”)
172. End If
173. ‘ Modify the properties of the retrieved DCB structure as appropriate.
174. ‘ WARNING: Make sure to modify the properties according to their supported values.
175. MyDCB.BaudRate = 9600
176. MyDCB.ByteSize = 8
177. MyDCB.Parity = NOPARITY
178. MyDCB.StopBits = ONESTOPBIT
179. ‘ Reconfigure LPT1 based on the properties of the modified DCB structure.
180. Success = SetCommState(hParallelPort, MyDCB)
181. If Success = False Then
182. Throw New CommException(“Unable to reconfigure LPT1”)
183. End If
184. ‘ Retrieve the current time-out settings.
185. Success = GetCommTimeouts(hParallelPort, MyCommTimeouts)
186. If Success = False Then
187. Throw New CommException(“Unable to retrieve current time-out settings”)
188. End If
189. ‘ Modify the properties of the retrieved COMMTIMEOUTS structure as appropriate.
190. ‘ WARNING: Make sure to modify the properties according to their supported values.
191. MyCommTimeouts.ReadIntervalTimeout = 0
192. MyCommTimeouts.ReadTotalTimeoutConstant = 0
193. MyCommTimeouts.ReadTotalTimeoutMultiplier = 0
194. MyCommTimeouts.WriteTotalTimeoutConstant = 0
195. MyCommTimeouts.WriteTotalTimeoutMultiplier = 0
196. ‘ Reconfigure the time-out settings, based on the properties of the modified COMMTIMEOUTS structure.
197. Success = SetCommTimeouts(hParallelPort, MyCommTimeouts)
198. If Success = False Then
199. Throw New CommException(“Unable to reconfigure the time-out settings”)
200. End If
201. ‘ Write data to LPT1.
202. ‘ Note: You cannot read data from a parallel port by calling the ReadFile function.
203. Console.WriteLine(“Writing the following data to LPT1: Test”)
204. Success = WriteFile(hParallelPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero)
205. If Success = False Then
206. Throw New CommException(“Unable to write to LPT1”)
207. End If
208. Catch ex As Exception
209. Console.WriteLine(Ex.Message)
210. Finally
211. ‘ Release the handle to LPT1.
212. Success = CloseHandle(hParallelPort)
213. If Success = False Then
214. Console.WriteLine(“Unable to release handle to LPT1”)
215. End If
216. End Try
217.
218. Console.WriteLine(“Press ENTER to quit”)
219. Console.ReadLine()
220. Membangun menu, klik Membangun solusi.
221. Pada Debug menu, klik mulai menjalankan aplikasi.

Anda mungkin menerima teks berikut di konsol:
Mengakses COM1 Porta serial
Menulis data berikut untuk COM1: uji

Membaca data berikut dari COM1: Serial Data
Mengakses port paralel LPT1

Menulis data berikut untuk LPT1: uji

Tekan ENTER untuk keluar dari
CatatanSerial Data mewakili data yang Anda baca dari serial port.
222. Untuk menutup aplikasi, tekan tombol ENTER di konsol.
Daftar Pustaka
http://support.microsoft.com/kb/823179/id-id

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s