Anda di halaman 1dari 16

Pemrograman port serial menggunakan fungsi DOS dan BIOS Untuk mengakses port serial kita dapat menggunakan

fungsi DOS untuk membaca data dan mengirim data. Berikut ini contoh port serial: #include (dos.h) /*mengirim karakter ke port serial */ Void put_async(char ch) { Bdos(04, ch, 0); { /* membaca karakter dari port serial*/ Void get_async(){ Return ((char) bdos (03, 0,0 ); } Fungsi ini secara otomatis menggunakan port serial default. Jika kita melakukan penggantian port pada MODE command, fungsi ini secara otomatis menggunakan port yang baru. Kita juga dapat menggunakan rutin dari BIOS yaitu fungsi bioscom() dengan bentuk umumnya Int bioscom(int mode, char val, int port) Dengan mode menunjukan operasi dari bioscom() MODE 0 1 2 3 FUNGSI Inisalisasi port Mentransmisikan 1 byte Menerima 1 byte Mengembalikan status port

Port serial yang akan diakses ditentukan oleh port dengan 0 menandakan COM1 dan 1 menandakan COM2 dan seterusnya. Fungsi ini ada didalam bios.h Sumber: Implementasi Pemrograman C++

MSCOMM adalah sebuah activeX control untuk mengakses port serial. Karena activeX maka MSCOMM tidak hanya bisa dipakau di VB. Saya juga pada saat belajar komunikasi serial pakai Delphi, juga menggunakan MSCOMM ini. Sebelum dipakai MSCOMM perlu di setting terlebih dahulu. 1. Pertama menentukan com mana yang akan dipakai: MSComm1.Comport ---> Integer, misal jika akan dipakai com1 MSCOMM1.Comport = 1 Note: pengalaman saya menggunakan MSComm pakai Delphi adalah comport maksimum adalah 9, jika comport=10 atau lebih pasti error. Nga tahu pada MSComm yang terbaru. 2. Kemudian setting baud rate, bit data, stop bit, parity. MSComm1.Setting ---> string Misal jika diinginkan baud rate 9600, 8 bit data, 1 stop bit dan non paritas, maka MSComm1.Setting = "9600,n,8,1" 3. Kemudian buka port tersebut MSComm1.PortOpen = true Note: pastikan ada error handle pada saat membuka COM, karena Windows tidak mengijinkan COM dibuka oleh lebih dari satu aplikasi, artinya jika COM sedang dipakai oleh sebuah aplikasi, maka aplikasi lain tidak akan bisa membuka com tersebut. Untuk menutup COM, tinggal MSComm1.PortOpen = False 4. Kemudian mengirim data MSComm1.Output = datanya. Misal ketika ingin mengirimkan AT Command ke sebuah modem GSM MSComm1.Output = "AT"& chr(13) --> Koreksi jika sintaknya salah 5. Membaca Data, data = MSComm1.Input untuk membaca data, pastikan dulu bahwa buffer input port serial data telah berisi data, gunakan InBufferCount Do While MSCOmm.InBufferCount = 0 DoEvents Loop Ukuran buffer input juga bisa di-set dengan menggunakan MSCOmm.InputLen, misal jika ingin menerima 2 karakter MSCOmm1.InputLen = 2 data = MSComm.Input MSComm juga bisa di-set untuk membangkitkan Interupsi (atau dalam istilah pemrograman Windows sebuah Event), misalnya saat menerima data atau mengirim data. Maaf saya tidak tahu caranya mengaktifkan Event MSComm di VB. Dan juga bisa mengontrol pin2 RS-232 lainnya, RTS atau CTS. MSComm1.RTSEnable = True Keterangan lengkap tentang MSComm dan contoh2nya saya yakin ada di

MSDN, karena saya juga belajar dari situ. Selamat mencoba dan semoga bermanfaat

http://support.microsoft.com/kb/823179/id-id Persyaratan The Daftar berikut menguraikan fitur perangkat keras, perangkat lunak, jaringan infrastruktur, dan paket layanan yang Anda butuhkan:

Microsoft Windows Server 2003, Microsoft Windows XP, atau Microsoft Windows 2000 Visual Basic.NET

Ini Artikel ini mengasumsikan bahwa Anda sudah familiar dengan topik-topik berikut:

Pemrograman dalam Visual Basic.NET Platform memohon layanan dalam Visual Basic.NET

Kembali ke atas Gunakan kontrol MSComm dalam Visual Basic.NET untuk mengakses port serial Karena tidak ada Microsoft.NET Framework kelas ada akses sumber daya komunikasi yang terhubung ke komputer Anda, Anda dapat menggunakan MSComm kontrol di Microsoft Visual Basic 6.0. The MSComm kontrol menyediakan komunikasi serial untuk aplikasi Anda oleh memungkinkan transmisi dan penerimaan data melalui serial port. Pada menerapkan dasar komunikasi serial dengan menggunakan modem, ikuti langkah berikut: 1. 2. 3. 4. 5. Mulai Microsoft Visual Studio.NET. Pada Berkas menu, titikBaru, lalu klik Project. Di bawah Jenis proyek, klik Visual Dasar proyek. Di bawah Pola acu, klik Konsol Aplikasi. Dalam Nama kotak, jenisMyConsoleApplication, lalu klikOke.

Secara default, Module1.vb dibuat. 6. Klik kanan MyConsoleApplicationproyek, dan kemudian klik Menambahkan referensi. 7. Klik COM tab, klik Microsoft Comm kontrol 6.0 di bawah Nama komponen, klikPilih, lalu klik Oke. Catatan Untuk menggunakan MSComm kontrol, Anda harus menginstal komponen COM terkait Microsoft Visual Basic 6.0 di komputer yang sama yang memiliki Microsoft Visual Studio.NET diinstal. Untuk informasi lebih lanjut tentang lisensi masalah ketika Anda menggunakan Visual Dasar 6.0 kontrol dalam Visual Studio.NET, klik nomor artikel di bawah ini untuk melihat artikel di dalam Basis Pengetahuan Microsoft:

318597 Kesalahan saat Anda menggunakan kontrol Visual Basic 6.0 dalam Visual Studio.NET 8. Ganti kode dalam Module1.vb dengan kode berikut contoh.
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 membangun dan menjalankan proyek ini. Anda akan menerima pesan output berikut: Membuka serial pelabuhan. Mengirim perintah perhatian ke modem. Menunggu data untuk datang kembali ke serial port...

Membaca data OK respon dalam serial pelabuhan. Menutup serial port. Kembali ke atas Menggunakan platform memohon layanan untuk memanggil fungsi Win32 API dalam Visual Basic.NET untuk akses port serial dan paralel Untuk melakukannya, ikuti langkah-langkah berikut: 1. 2. 3. 4. 5. Mulai Microsoft Visual Studio.NET. Pada Berkas menu, titikBaru, lalu klik Project. Di bawah Jenis proyek, klik Visual Dasar proyek. Di bawah Pola acu, klik Konsol Aplikasi. Dalam Nama kotak teks, ketikMyConsoleApplication, lalu klikOke.

Secara default, Module1.vb dibuat. 6. Menambahkan kode berikut ke Module1.vb sebelumModul Module1 pernyataan:
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 di Kernel32.dll Untuk memanggil fungsi tidak dikelola dari Anda dikelola Visual Basic.NET aplikasi, Anda harus menyatakan rujukan struktur yang Anda lulus sebagai parameter ke fungsi tidak dikelola, dan Anda harus menyatakan konstanta yang Anda lulus sebagai parameter ke fungsi tidak dikelola. Untuk melakukannya, tambahkan kode berikut ke Module1.vb setelah Modul Module1 pernyataan:
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. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55.

Public EofChar As Byte Public EvtChar As Byte Public wReserved1 As Int16 'Reserved; Do Not Use End Structure Public Structure COMMTIMEOUTS Public ReadIntervalTimeout As Int32 Public ReadTotalTimeoutMultiplier As Int32 Public ReadTotalTimeoutConstant As Int32 Public WriteTotalTimeoutMultiplier As Int32 Public WriteTotalTimeoutConstant As Int32 End Structure 'Declare constants. Public Const GENERIC_READ As Int32 = &H80000000 Public Const GENERIC_WRITE As Int32 = &H40000000 Public Const OPEN_EXISTING As Int32 = 3 Public Const FILE_ATTRIBUTE_NORMAL As Int32 = &H80 Public Const NOPARITY As Int32 = 0 Public Const ONESTOPBIT As Int32 = 0

'Declare references to external functions. Public Declare Auto Function CreateFile Lib "kernel32.dll" _ (ByVal lpFileName As String, ByVal dwDesiredAccess As Int32, _ 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 paralel port, Anda harus mendapatkan pegangan untuk port yang tepat dan kemudian mengkonfigurasi port komunikasi. Untuk melakukannya, tambahkan kode inisialisasi berikut untuk Module1.vb Setelah Sub utama pernyataan. Catatan Untuk membangun komunikasi dengan LPTx Port, Anda harus menghentikan layanan Print Spooler. Untuk melakukannya, gunakan alat layanan dalam alat-alat administratif.
80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. ' Declare the local variables that you will use in the code. Dim hSerialPort, hParallelPort As IntPtr Dim Success As Boolean Dim MyDCB As DCB Dim MyCommTimeouts As COMMTIMEOUTS Dim BytesWritten, BytesRead As Int32 Dim Buffer() As Byte ' Declare the variables to use for encoding. Dim oEncoder As New System.Text.ASCIIEncoding Dim oEnc As System.Text.Encoding = oEncoder.GetEncoding(1252)

' Convert String to Byte(). Buffer = oEnc.GetBytes("Test") Try ' Access the serial port. Console.WriteLine("Accessing the COM1 serial port") ' Obtain a handle to the COM1 serial port. 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 timeout 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 timeout 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 timeout 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 timeout 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. 212. 213. 214. 215. 216. 217. 218. 219.

' Release the handle to LPT1. Success = CloseHandle(hParallelPort) If Success = False Then Console.WriteLine("Unable to release handle to LPT1") End If End Try Console.WriteLine("Press ENTER to quit") Console.ReadLine()

220. 221.

Pada Bangun menu, klik Bangun Solusi. Pada Debug menu, klikMulai untuk menjalankan aplikasi.

Anda akan menerima teks berikut di konsol: Mengakses COM1 serial port Menulis data berikut untuk COM1: tes Baca berikut data dari COM1: Serial Data Mengakses paralel port LPT1 Menulis data berikut untuk LPT1: tes Tekan ENTER untuk berhenti Catatan Serial Data mewakili data yang Anda membaca dari serial port. 222. Untuk menutup aplikasi, tekan tombol ENTER di konsol.

Kembali ke atas Daftar kode sampel (Module1.vb) Sebelum Anda menggunakan kode contoh berikut, ganti COM1 dengan nama serial port, dan ganti LPT1 dengan nama Anda paralel port. Catatan Kode berikut bekerja hanya ketika perangkat serial dan paralel perangkat terhubung ke port sesuai pada komputer. Jika Anda tidak menghubungkan perangkat ini dan Anda menjalankan program, program menunggu selamanya.
Option Strict On ' Define a CommException class that inherits from the ApplicationException class. ' Then throw an object of type CommException when you receive an error message. Class CommException Inherits ApplicationException Sub New(ByVal Reason As String) MyBase.New(Reason) End Sub

End Class Module Module1 'Declare structures Public Structure DCB Public DCBlength As Int32 Public BaudRate As Int32 Public fBitFields As Int32 Public wReserved As Int16 Public XonLim As Int16 Public XoffLim As Int16 Public ByteSize As Byte Public Parity As Byte Public StopBits As Byte Public XonChar As Byte Public XoffChar As Byte Public ErrorChar As Byte Public EofChar As Byte Public EvtChar As Byte Public wReserved1 As Int16 'Reserved; Do Not Use End Structure Public Structure COMMTIMEOUTS Public ReadIntervalTimeout As Int32 Public ReadTotalTimeoutMultiplier As Int32 Public ReadTotalTimeoutConstant As Int32 Public WriteTotalTimeoutMultiplier As Int32 Public WriteTotalTimeoutConstant As Int32 End Structure 'Declare constants. Public Const GENERIC_READ As Int32 = &H80000000 Public Const GENERIC_WRITE As Int32 = &H40000000 Public Const OPEN_EXISTING As Int32 = 3 Public Const FILE_ATTRIBUTE_NORMAL As Int32 = &H80 Public Const NOPARITY As Int32 = 0 Public Const ONESTOPBIT As Int32 = 0 'Declare references to external functions. Public Declare Auto Function CreateFile Lib "kernel32.dll" _ (ByVal lpFileName As String, ByVal dwDesiredAccess As Int32, _ ByVal dwShareMode As Int32, ByVal lpSecurityAttributes As IntPtr, _ ByVal dwCreationDisposition As Int32, ByVal dwFlagsAndAttributes As Int32, _ ByVal hTemplateFile As IntPtr) As IntPtr Public Declare Auto Function GetCommState Lib "kernel32.dll" (ByVal nCid As IntPtr, _ ByRef lpDCB As DCB) As Boolean Public Declare Auto Function SetCommState Lib "kernel32.dll" (ByVal nCid As IntPtr, _ ByRef lpDCB As DCB) As Boolean Public Declare Auto Function GetCommTimeouts Lib "kernel32.dll" (ByVal hFile As IntPtr, _ ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean

Public Declare Auto Function SetCommTimeouts Lib "kernel32.dll" (ByVal hFile As IntPtr, _ ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean Public Declare Auto Function WriteFile Lib "kernel32.dll" (ByVal hFile As IntPtr, _ ByVal lpBuffer As Byte(), ByVal nNumberOfBytesToWrite As Int32, _ ByRef lpNumberOfBytesWritten As Int32, ByVal lpOverlapped As IntPtr) As Boolean Public Declare Auto Function ReadFile Lib "kernel32.dll" (ByVal hFile As IntPtr, _ ByVal lpBuffer As Byte(), ByVal nNumberOfBytesToRead As Int32, _ ByRef lpNumberOfBytesRead As Int32, ByVal lpOverlapped As IntPtr) As Boolean Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean Sub Main() ' Declare local variables that you will use in the code. Dim hSerialPort, hParallelPort As IntPtr Dim Success As Boolean Dim MyDCB As DCB Dim MyCommTimeouts As COMMTIMEOUTS Dim BytesWritten, BytesRead As Int32 Dim Buffer() As Byte ' Declare variables to use for encoding. Dim oEncoder As New System.Text.ASCIIEncoding Dim oEnc As System.Text.Encoding = oEncoder.GetEncoding(1252) ' Convert String to Byte(). Buffer = oEnc.GetBytes("Test") Try ' Serial port. Console.WriteLine("Accessing the COM1 serial port") ' Obtain a handle to the COM1 serial port. hSerialPort = CreateFile("COM1", GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero) ' Verify that the obtained handle is valid. If hSerialPort.ToInt32 = -1 Then Throw New CommException("Unable to obtain a handle to the COM1 port") End If ' Retrieve the current control settings. Success = GetCommState(hSerialPort, MyDCB) If Success = False Then Throw New CommException("Unable to retrieve the current control settings") End If ' Modify the properties of the retrieved DCB structure as appropriate.

' WARNING: Make sure to modify the properties according to their supported values. MyDCB.BaudRate = 9600 MyDCB.ByteSize = 8 MyDCB.Parity = NOPARITY MyDCB.StopBits = ONESTOPBIT ' Reconfigure COM1 based on the properties of the modified DCB structure. Success = SetCommState(hSerialPort, MyDCB) If Success = False Then Throw New CommException("Unable to reconfigure COM1") End If ' Retrieve the current time-out settings. Success = GetCommTimeouts(hSerialPort, MyCommTimeouts) If Success = False Then Throw New CommException("Unable to retrieve current time-out settings") End If ' Modify the properties of the retrieved COMMTIMEOUTS structure as appropriate. ' WARNING: Make sure to modify the properties according to their supported values. MyCommTimeouts.ReadIntervalTimeout = 0 MyCommTimeouts.ReadTotalTimeoutConstant = 0 MyCommTimeouts.ReadTotalTimeoutMultiplier = 0 MyCommTimeouts.WriteTotalTimeoutConstant = 0 MyCommTimeouts.WriteTotalTimeoutMultiplier = 0 ' Reconfigure the time-out settings, based on the properties of the modified COMMTIMEOUTS structure. Success = SetCommTimeouts(hSerialPort, MyCommTimeouts) If Success = False Then Throw New CommException("Unable to reconfigure the time-out settings") End If ' Write data to COM1. Console.WriteLine("Writing the following data to COM1: Test") Success = WriteFile(hSerialPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero) If Success = False Then Throw New CommException("Unable to write to COM1") End If ' Read data from COM1. Success = ReadFile(hSerialPort, Buffer, BytesWritten, BytesRead, IntPtr.Zero) If Success = False Then Throw New CommException("Unable to read from COM1") End If Catch ex As Exception Console.WriteLine(Ex.Message) Finally ' Release the handle to COM1. Success = CloseHandle(hSerialPort) If Success = False Then Console.WriteLine("Unable to release handle to COM1") End If End Try

Try ' Parallel port. Console.WriteLine("Accessing the LPT1 parallel port") ' Obtain a handle to the LPT1 parallel port. hParallelPort = CreateFile("LPT1", GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero) ' Verify that the obtained handle is valid. If hParallelPort.ToInt32 = -1 Then Throw New CommException("Unable to obtain a handle to the LPT1 port") End If ' Retrieve the current control settings. Success = GetCommState(hParallelPort, MyDCB) If Success = False Then Throw New CommException("Unable to retrieve the current control settings") End If ' Modify the properties of the retrieved DCB structure as appropriate. ' WARNING: Make sure to modify the properties according to their supported values. MyDCB.BaudRate = 9600 MyDCB.ByteSize = 8 MyDCB.Parity = NOPARITY MyDCB.StopBits = ONESTOPBIT ' Reconfigure LPT1 based on the properties of MyDCB. Success = SetCommState(hParallelPort, MyDCB) If Success = False Then Throw New CommException("Unable to reconfigure LPT1") End If ' Reconfigure LPT1 based on the properties of the modified DCB structure. Success = GetCommTimeouts(hParallelPort, MyCommTimeouts) If Success = False Then Throw New CommException("Unable to retrieve current time-out settings") End If ' Modify the properties of the retrieved COMMTIMEOUTS structure as appropriate. ' WARNING: Make sure to modify the properties according to their supported values. MyCommTimeouts.ReadIntervalTimeout = 0 MyCommTimeouts.ReadTotalTimeoutConstant = 0 MyCommTimeouts.ReadTotalTimeoutMultiplier = 0 MyCommTimeouts.WriteTotalTimeoutConstant = 0 MyCommTimeouts.WriteTotalTimeoutMultiplier = 0 ' Reconfigure the time-out settings, based on the properties of the modified COMMTIMEOUTS structure. Success = SetCommTimeouts(hParallelPort, MyCommTimeouts) If Success = False Then Throw New CommException("Unable to reconfigure the time-out settings") End If ' Write data to LPT1. ' Note: You cannot read data from a parallel port by calling the ReadFile function.

Console.WriteLine("Writing the following data to LPT1: Test") Success = WriteFile(hParallelPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero) If Success = False Then Throw New CommException("Unable to write to LPT1") End If Catch ex As Exception Console.WriteLine(Ex.Message) Finally ' Release the handle to LPT1. Success = CloseHandle(hParallelPort) If Success = False Then Console.WriteLine("Unable to release handle to LPT1") End If End Try Console.WriteLine("Press ENTER to quit") Console.ReadLine() End Sub End Module

Kembali ke atas Mengatasi masalah

Ketika Anda menjalankan aplikasi, Anda akan menerima berikut pesan galat: System.NullReferenceException: objek referensi tidak diatur ke contoh sebuah objek. Anda mungkin menerima ini pesan galat karena deklarasi fungsi Anda salah. Kesalahan ini pesan biasanya terjadi ketika Anda Deklarasi berisi ByVal parameter bukannya ByRef parameter.

Aplikasi Anda mungkin menunggu selamanya ketika Anda memohon ReadFile fungsi. Perilaku ini biasanya terjadi ketika Anda mengatur membaca time-out ke nol di diakses COMMTIMEOUTS struktur. Untuk mengatasi masalah ini, mengubah properti COMMTIMEOUTS struktur, yang sesuai.

http://www.innovativeelectronics.com/innovative_electronics/download_files/buletin/Buletin0608.pdf

PDF

Anda mungkin juga menyukai