Seri porttan datanın gelmesi nasıl beklenir ?

Başlatan hasangurlek, 25 Nisan 2010, 06:46:51

hasangurlek

Uygulamayı esir edip kitlemeden, multi thread kullanmadan sadece veri geldiğinde işleyen basit ama etkili bir yöntemdir. Kontrol tamamen MCU yazılımı tarafından yapılabilir yani MCU her canı istediğinde datayı gönderebilir, PC sadece data geldiğinde alır ve işler. Ayrıca iletişim donanımdan PC e doğru tek yönlü olduğu için hızlıdır.

Bu bölüm sınıf veya gerekli ilaveler yapılarak component vs. (lisanslı kullanıcılar için) olarak oluşturulabilir;

    ''' <summary>
    ''' Serial port example
    ''' </summary>
    ''' <remarks></remarks>
    ''' 
    Public Class MySerialPort
        Dim Serialport1 As New IO.Ports.SerialPort

#Region " VARIABLES "
        Dim _PortNumber As String = "COM1"
        Dim _Baud As Int32 = 57600
        Dim _Bits As Int32 = 8
#End Region

#Region " PROPERTIES "
        ''' <summary>
        ''' Assign a number to serial port
        ''' </summary>
        ''' <value>Port number as string like "COM3"</value>
        ''' <remarks></remarks>
        Public WriteOnly Property PortNumber()
            Set(ByVal value)
                _PortNumber = value
            End Set
        End Property

        ''' <summary>
        ''' Assign a baud rate to serial port
        ''' </summary>
        ''' <value>Baud rate as integer like 9600</value>
        ''' <remarks></remarks>
        Public WriteOnly Property Baud()
            Set(ByVal value)
                _Baud = value
            End Set
        End Property

        ''' <summary>
        ''' Assign a number for data bits to serial port
        ''' </summary>
        ''' <value>Number of data bits as integer like 8</value>
        ''' <remarks></remarks>
        Public WriteOnly Property Bits()
            Set(ByVal value)
                _Bits = value
            End Set
        End Property

        Private ReadOnly Property Resolution()
            Get
                Return 5000 / 1023
            End Get
        End Property
#End Region

#Region " METHODS "
        ''' <summary>
        ''' Please don't call this method until assigned all required data, 
        ''' otherwise the port will be initialized with default values
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub InitializePort()
            Serialport1.PortName = _PortNumber
            Serialport1.BaudRate = _Baud
            Serialport1.DataBits = _Bits
            Serialport1.Parity = IO.Ports.Parity.None
            Serialport1.StopBits = IO.Ports.StopBits.One
            Serialport1.Handshake = IO.Ports.Handshake.RequestToSend
            Serialport1.RtsEnable = False   ' RTS kullanımı için : True
            Serialport1.DtrEnable = False    ' DTR kullanımı için : True
            Serialport1.ReceivedBytesThreshold = 2 ' DataReceived olayının tetiklenmesi (kaç bayt data alındığında?)
            Serialport1.ReadTimeout = 1000
            AddHandler Serialport1.DataReceived, AddressOf ReceivedData ' Data alındı olayı
            'AddHandler Serialport1.PinChanged, AddressOf ChangedPin ' Pin değişimi olayı
            'AddHandler Serialport1.ErrorReceived, AddressOf OccurredErr ' Hata olayı
        End Sub

        ''' <summary>
        ''' Opens the port for communication
        ''' </summary>
        ''' <returns>True if successful, otherwise false</returns>
        ''' <remarks></remarks>
        Public Function OpenPort() As Boolean
            If Not Serialport1 Is Nothing Then
                If Not Serialport1.IsOpen Then
                    Try
                        Serialport1.Open()
                    Catch ex As System.Exception
                        MessageBox.Show(ex.ToString)
                    Finally
                        If Serialport1.IsOpen Then
                            OpenPort = True
                        End If
                    End Try
                End If
            End If
        End Function

        ''' <summary>
        ''' Closes the port, if it is available
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub ClosePort()
            If Not Serialport1 Is Nothing Then
                Try
                    If Serialport1.IsOpen Then
                        Serialport1.Close()
                    End If
                    Serialport1.Dispose()
                Catch ex As System.Exception
                    MessageBox.Show(ex.ToString)
                Finally
                    Serialport1 = Nothing
                End Try
                RemoveHandler Serialport1.DataReceived, AddressOf ReceivedData
                'RemoveHandler Serialport1.PinChanged, AddressOf ChangedPin
                'RemoveHandler Serialport1.ErrorReceived, AddressOf OccurredErr
            End If
        End Sub

        Private Sub ReceivedData(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
            Dim _ReceivedData(1) As Byte
            Serialport1.Read(_ReceivedData, 0, 2) ' Bellekten istenen adresten, istenen kadarını byte olarak arraya alır
            Dim _Temp = CInt((_ReceivedData(0) * 256) + _ReceivedData(1))
            Form2.PrBar_TEMP.Value = _Temp ' Progresbar.maximum : 5000, minumum : 0
            Form2.Txt_TEMP.Text = Format((_Temp * Resolution / 10), "0.00").ToString
        End Sub

        Private Sub ChangedPin(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialPinChangedEventArgs)

        End Sub

        Private Sub OccurredErr(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialErrorReceivedEventArgs)

        End Sub
#End Region
    End Class


ReceivedData eventi AddHandler adresi düzeltilerek form sınıfı içinde yerleştirilebilir.
Resulotion propertyisi 5 volt ve 10 bit AD çevrim çözünürlüğüne göre ayarlanmıştır.
Data trasferi 2 bayt iletişimde bir kesme oluşturacak şekilde ayarlanmıştır.
Donanımsal kontrol pinlerinin seviye değişimi ve hata eventleri kullanılabilir.
Kullanım amacı LM35 den elde edilen 2 bayt verinin PC tarafında işlenmesi üzerinedir.



İletişimin başlatılması ve durdurulması form olaylarına bağlanmıştır ama her hangi bir şekilde kullanılabilir;

Public Class Form2
    Dim MyPort As New EDSoft.MySerialPort

    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        With MyPort
            .PortNumber = "COM9"
            .Baud = 19200
            .Bits = 8
            .InitializePort()
        End With
        Do Until MyPort.OpenPort
            If MessageBox.Show("Port açılamadı, tekrar denensin mi ?", "Hata", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) = Windows.Forms.DialogResult.Cancel Then
                Exit Do
            End If
        Loop
    End Sub

    Private Sub Form2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        MyPort.ClosePort()
        MyPort = Nothing
    End Sub

End Class


MySerialPort sınıfı bende EDSoft kütüphanesi içinde olduğu için Dim MyPort As New EDSoft.MySerialPort olarak gözükmektedir, siz objeyi oluştururken kendinize göre düzeltmelisiniz.

Form üzerinde PrBar_TEMP adında bir progressbar ve Txt_TEMP adıyla bir textbox bulunması gereklidir.

Özel verdiğim kurslarda kullandığım bir uygulamaydı ama USB üzerine çalıştığımdan dolayı epeydir ihtiyaç duymadım ve bir arkadaşımız istediği için burada paylaştım. İstediğiniz gibi kendi projelerinize adapte edip kullanabilirsiniz. Takıldığınız yerde sorabilirsiniz.
http://www.cyber-warrior.org, Although they like whiteness, sometimes twilight is required...  Hala evlilermi bilinmez ama kesinlikle artık uygun değiller !!!