[an error occurred while processing this directive]
как раз от туда пример и брал там одна функция для обоих
(«Телесистемы»: Конференция «Микроконтроллеры и их применение»)

миниатюрный аудио-видеорекордер mAVR

Отправлено whale 15 июля 2005 г. 13:25
В ответ на: GetCommState это для последовательного порта ващето. А лучше посмотри MSDN. отправлено Codavr 15 июля 2005 г. 12:42




HOW TO: Access Serial Ports and Parallel Ports by Using Microsoft Visual Basic .NET
View products that this article applies to.
Article ID : 823179
Last Review : July 12, 2004
Revision : 1.0

IN THIS TASK
• SUMMARY• Requirements
• Create a Console Application
• Create a CommException Class for Error-Handling
• Declare Structures and Constants That Are in Kernel32.dll
• Declare References to External Procedures That Are in Kernel32.dll
• Declare Local Variables
• Obtain a Handle to a Port
• Retrieve and Modify the Control Settings
• Retrieve and Modify the Time-out Settings
• Write Data to a Port
• Read Data from a Port
• Release a Handle to a Port
• Sample Code Listing (Module1.vb)
• Verify That the Code Works
• Troubleshoot

• REFERENCES

On this page
SUMMARY
Requirements
Create a Console Application
Create a CommException Class for Error-Handling
Declare Structures and Constants That Are in Kernel32.dll
Declare References to External Procedures That Are in Kernel32.dll
Declare Local Variables
Obtain a Handle to a Port
Retrieve and Modify the Control Settings
Retrieve and Modify the Time-Out Settings
Write Data to a Port
Read Data from a Port
Release a Handle to a Port
Sample Code Listing (Module1.vb)
Verify That the Code Works
Troubleshoot
REFERENCES
APPLIES TO

SUMMARY
This step-by-step article describes how to access serial ports and how to access parallel ports by using Microsoft Visual Basic .NET. This article also contains sample code that illustrates the concepts that are discussed in this article.

back to the top
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required: • Microsoft Windows 2000, Microsoft Windows XP, or Microsoft Windows Server 2003
• Visual Basic .NET
This article assumes that you are familiar with the following topics: • Programming with Visual Basic .NET
• Platform invoke services in Visual Basic .NET
back to the top
Create a Console Application
1. Start Microsoft Visual Studio .NET.
2. On the File menu, point to New, and then click Project.
3. Under Project Types, click Visual Basic Projects.
4. Under Templates, click Console Application.
5. In the Name text box, type MyConsoleApplication, and then click OK.

By default, Module1.vb is created.
6. Add the following code to Module1.vb before the Module Module1 statement:
Option Strict On

back to the top
Create a CommException Class for Error-Handling
To perform error-handling, define a CommException class that inherits from the ApplicationException class, and then throw an object of type CommException when you receive an error message. To define CommException, add the following code to Module1.vb after the Option Strict On statement:
Class CommException
Inherits ApplicationException
Sub New(ByVal Reason As String)
MyBase.New(Reason)
End Sub
End Class
back to the top
Declare Structures and Constants That Are in Kernel32.dll
To call unmanaged functions from your managed Visual Basic .NET application, you must declare references to the structures that you pass as parameters to the unmanaged functions, and you must declare the constants that you pass as parameters to the unmanaged functions. To do this, add the following code to Module1.vb after the Module Module1 statement:
Public Structure DCB
Public DCBlength As Int32
Public BaudRate As Int32
Public fBitFields As Int32 'See Comments in Win32API.Txt
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

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
back to the top
Declare References to External Procedures That Are in Kernel32.dll
To call unmanaged functions from your managed Visual Basic .NET application, declare references to the unmanaged functions by using the Declare keyword. To do this, add the following code to Module1.vb before the Sub Main() statement:
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
back to the top
Declare Local Variables
To declare local variables that you may use in your code, add the following initialization code to Module1.vb after the Sub Main() statement:
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")
back to the top
Obtain a Handle to a Port
You must obtain a handle to the appropriate port before you can access a serial port or access a parallel port. To obtain a handle, call the CreateFile function and pass the appropriate port name as the lpFileName parameter. To obtain a handle to the COM1 serial port, use the following code:
hSerialPort = CreateFile("COM1", GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)
To obtain a handle to the LPT1 parallel port, use the following code:
hParallelPort = CreateFile("LPT1", GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)
back to the top
Retrieve and Modify the Control Settings
To configure the control settings for your serial port or to configure the control settings for your parallel port, follow these steps: 1. Call the GetCommState function.
2. Modify the retrieved DCB structure.

Note Modify only the properties that should be changed for your device. Do not modify the other properties.
3. Call the SetCommState function to reconfigure the corresponding port.

To reconfigure COM1, use the following code:
Success = GetCommState(hSerialPort, MyDCB)
' Modify the properties of MyDCB as appropriate.
' WARNING: Make sure to modify the properties in accordance with their supported values.
MyDCB.BaudRate = 9600
MyDCB.ByteSize = 8
MyDCB.Parity = NOPARITY
MyDCB.StopBits = ONESTOPBIT
' Reconfigure COM1 based on the properties of MyDCB.
Success = SetCommState(hSerialPort, MyDCB)
To reconfigure LPT1, use the following code:
Success = GetCommState(hParallelPort, MyDCB)
' Modify the properties of MyDCB as appropriate.
' WARNING: Make sure to modify the properties in accordance with 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)

back to the top
Retrieve and Modify the Time-Out Settings
To configure the time-out settings for your serial port or to configure the time-out settings for your parallel port, follow these steps:1. Call the GetCommTimeouts function.
2. Modify the retrieved COMMTIMEOUTS structure.
3. Call the SetCommTimeouts function to reconfigure the time-out settings for the corresponding port.
To reconfigure the time-out settings for COM1, use the following code:
Success = GetCommTimeouts(hSerialPort, MyCommTimeouts)
' Modify the properties of MyCommTimeouts as appropriate.
' WARNING: Make sure to modify the properties in accordance with 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 MyCommTimeouts.
Success = SetCommTimeouts(hSerialPort, MyCommTimeouts)
To reconfigure the time-out settings for LPT1, use the following code:
Success = GetCommTimeouts(hParallelPort, MyCommTimeouts)
' Modify the properties of MyCommTimeouts as appropriate.
' WARNING: Make sure to modify the properties in accordance with 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 MyCommTimeouts.
Success = SetCommTimeouts(hParallelPort, MyCommTimeouts)

back to the top
Write Data to a Port
To write data to a serial port or to write data to a parallel port, call the WriteFile function. To write data to COM1, use the following code:
Success = WriteFile(hSerialPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero)
To write data to LPT1, use the following code:
Success = WriteFile(hParallelPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero)
back to the top
Read Data from a Port
To read data from a serial port, call the ReadFile function. To read data from COM1, use the following code:
Success = ReadFile(hSerialPort, Buffer, BytesWritten, BytesRead, IntPtr.Zero)
Note You cannot read data from a parallel port by calling the ReadFile function.

back to the top
Release a Handle to a Port
To release a handle to a port, call the CloseHandle function. To release a handle to COM1, use the following code:
Success = CloseHandle(hSerialPort)
To release a handle to LPT1, use the following code:
Success = CloseHandle(hParallelPort)
back to the top
Sample Code Listing (Module1.vb)
Before you use the following code, replace COM1 with the name of your serial port and replace LPT1 with the name of your parallel port.

Note The following code works only when serial devices and parallel devices are connected to the corresponding ports on your computer. If do not connect these devices and you run the program, the program waits indefinitely.
Option Strict On

Class CommException
Inherits ApplicationException
Sub New(ByVal Reason As String)
MyBase.New(Reason)
End Sub
End Class

Module Module1

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

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

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()

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 MyDCB as appropriate.
' WARNING: Make sure to modify the properties in accordance with their supported values.
MyDCB.BaudRate = 9600
MyDCB.ByteSize = 8
MyDCB.Parity = NOPARITY
MyDCB.StopBits = ONESTOPBIT
' Reconfigure COM1 based on the properties of MyDCB.
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 MyCommTimeouts as appropriate.
' WARNING: Make sure to modify the properties in accordance with 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 MyCommTimeouts.
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 MyDCB as appropriate.
' WARNING: Make sure to modify the properties in accordance with 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
' Retrieve the current time-out settings.
Success = GetCommTimeouts(hParallelPort, MyCommTimeouts)
If Success = False Then
Throw New CommException("Unable to retrieve current time-out settings")
End If
' Modify the properties of MyCommTimeouts as appropriate.
' WARNING: Make sure to modify the properties in accordance with 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 MyCommTimeouts.
Success = SetCommTimeouts(hParallelPort, MyCommTimeouts)
If Success = False Then
Throw New CommException("Unable to reconfigure the time-out settings")
End If
' Write data to LPT1.
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
back to the top
Verify That the Code Works
1. On the Build menu, click Build Solution.
2. On the Debug menu, click Start to run the application.

You may receive the following text in the console:
Accessing the COM1 serial portWriting the following data to COM1: Test
Read the following data from COM1: Serial DataAccessing the LPT1 parallel port
Writing the following data to LPT1: Test
Press ENTER to quit


Note Serial Data is a placeholder for the data that you read from the serial port.
3. To quit the application, press the ENTER key in the console.
back to the top
Troubleshoot
• When you run the application, you may receive the following error message:
System.NullReferenceException: Object reference not set to an instance of an object.
You may receive this error message because your function declarations are incorrect. This error message typically occurs when your declarations contain ByVal parameters instead of ByRef parameters.
• Your application may wait indefinitely when you invoke the ReadFile function. This behavior typically occurs when you set the read time-outs to zero in the MyCommTimeouts structure. To resolve this issue, modify the properties of the MyCommTimeouts structure, as appropriate.
back to the top
Back to the top

REFERENCES
For more information, visit the following Microsoft Web sites:
Communications Resources
http://msdn.microsoft.com/library/en-us/devio/base/communications_resources.asp
Interoperating with Unmanaged Code
http://msdn.microsoft.com/library/en-us/cpguide/html/cpconinteroperatingwithunmanagedcode.asp
System.Runtime.InteropServices Namespace
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemRuntimeInteropServices.asp
DllImportAttribute Class
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemRuntimeInteropServicesDllImportAttributeClassTopic.asp
The Windows API and Other Dynamic-Link Libraries
http://msdn.microsoft.com/library/en-us/modcore/html/deovrthewindowsapiotherdynamiclinklibraries.asp
Understanding Handles
http://msdn.microsoft.com/library/en-us/modcore/html/deovrUnderstandingHandles.asp
back to the top
Back to the top


--------------------------------------------------------------------------------

APPLIES TO
• Microsoft Visual Basic .NET 2003 Standard Edition
• Microsoft Visual Basic .NET 2002 Standard Edition

Back to the top

Keywords: kbhowtomaster kb32bitonly kbkern32dll kbinterop kbapi kbconsole kbappdev kbdll kbprogramming kbcommport kbserial kbsample kbconfig kbsdk KB823179

Back to the top
Article Translations
FrenchGermanJapaneseKoreanPolishRussianSimplified ChineseSpanishTurkish

Related Support Centers
• Microsoft Visual Basic .NET 2002

• Microsoft Visual Basic .NET 2003


Составить ответ  |||  Конференция  |||  Архив

Ответы


Отправка ответа

Имя (обязательно): 
Пароль: 
E-mail: 
NoIX ключ Запомнить

Тема (обязательно):
Сообщение:

Ссылка на URL: 
Название ссылки: 

URL изображения: 


Перейти к списку ответов  |||  Конференция  |||  Архив  |||  Главная страница  |||  Содержание  |||  Без кадра

E-mail: info@telesys.ru