none
How to use the interrupt routine to service a serial com port

    Question

  • Hi guys,

    May i know how to fire an event using the serial port interrupt method in visual basic windows form? Currently, now i am using the polling method which is using the timer event to continuously poll the port every 1sec.

    But now i would like to change to the interrupt method which will fire up the same event without using the timer event.

    the below is my codes using the timer/polling event

    Imports System.Data.SqlClient
    Imports System.data
    Imports System.Drawing.Image
    Imports System.IO.Ports
    Imports System.Runtime.Remoting.Messaging ' used with asynchronous delegates
    
    
    
    Public Class ReceivedSMS
    
    
    
        Private WithEvents serialPort As New IO.Ports.SerialPort
    
    
        Dim receivedData As String
    
        Dim da As SqlDataAdapter
        Dim conn As SqlConnection
        Dim bsource As BindingSource = New BindingSource()
        Dim ds As DataSet
        Dim sql As String
        Dim inc As Integer
        Dim pnum As String
        Dim msg As String
        Dim dsNewRow As DataRow
        Dim dsColumn As DataColumn
        Dim MySoundPlayer As New System.Media.SoundPlayer
        Dim myCommand As New SqlCommand(Sql, conn)
        Dim str2 As String
    
    
    
        'new dataset for table AlarmsInBuilding
    
        Dim da1 As SqlDataAdapter
        Dim conn1 As SqlConnection
    
        Dim ds1 As DataSet
        Dim sql1 As String
        Dim dsNewRow1 As DataRow
        Dim myCommand1 As New SqlCommand(sql1, conn1)
        Dim dr As SqlDataReader
        'AUTOINCREMENT
        Dim n As Integer
        Dim numbers() As Integer
        Dim StartFrom As Integer
        Dim EndAt As Integer
        Dim MaxRows As Integer
    
    
        Dim da2 As SqlDataAdapter
        Dim conn2 As SqlConnection
        Dim ds2 As DataSet
        Dim sql2 As String
    
        Dim da3 As SqlDataAdapter
    
        Dim ds3 As DataSet
        Dim sql3 As String
    
    
    
     
    
    
       
        
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            '---display all the serial port names on the local computer---
            For i As Integer = 0 To _
            My.Computer.Ports.SerialPortNames.Count - 1
                ComboBox1.Items.Add( _
                My.Computer.Ports.SerialPortNames(i))
            Next
            Button1.Enabled = True
    
    
    
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Timer1.Enabled = True
    
    
            Try
                '---close the serial port if it is open---
                If serialPort.IsOpen Then
                    serialPort.Close()
                End If
    
                '---configure the various parameters of the serial port---
                With serialPort
                    .PortName = ComboBox1.Text
                    .BaudRate = 9600
                    .Parity = IO.Ports.Parity.None
                    .DataBits = 8
                    .StopBits = IO.Ports.StopBits.One
    
                End With
    
                '---open the serial port---
                serialPort.Open()
                MsgBox(serialPort.PortName & " is Connected." & System.DateTime.Now, MsgBoxStyle.Exclamation)
    
    
    
    
                'connection for the AlarmLogHistory
                Dim connectionString As String = "Data Source=ITCU-24\SQLEXPRESS;Initial Catalog=Flexlink;" & "Integrated Security=SSPI;"
                conn = New SqlConnection(connectionString)
                sql = "SELECT * FROM  AlarmHistory"
                da = New SqlDataAdapter(sql, conn)
                ds = New DataSet()
                Dim commandBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
                da.Fill(ds, "AlarmHistory")
    
              
                'same database so one connection will do
                sql2 = "SELECT * FROM CustDetail"
                ds2 = New DataSet()
                da2 = New SqlDataAdapter(sql2, conn)
                Dim commandBuilder2 As SqlCommandBuilder = New SqlCommandBuilder(da2)
                da2.Fill(ds2, "CustDetail")
    
    
    
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
    
    
            '---update the status of the serial port and
            ' enable/disable the buttons---
            Button1.Enabled = False
            Button2.Enabled = True
    
    
    
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    
    
    
            Try
                '---close the serial port---
                serialPort.Close()
                '---update the status of the serial port and
                ' enable/disable the buttons---
                MsgBox(serialPort.PortName & " disconnected.", MsgBoxStyle.Critical)
                Button1.Enabled = True
                Button2.Enabled = False
                Timer1.Stop()
                ' Timer2.Stop()
    
    
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
    
    
        End Sub
    
        Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    
    
            serialPort.Write("AT+CMGL=""REC UNREAD""" & vbCrLf) 'set command message format to text mode(1)
            receivedData = serialPort.ReadExisting()
    
    
            Dim dsNewRow As DataRow
            dsNewRow = ds.Tables("AlarmHistory").NewRow()
    
            Dim SplitStringsArray() As String = receivedData.Split(Convert.ToChar(","))
    
            Dim result As String = String.Empty
            If SplitStringsArray.GetUpperBound(0) >= 2 Then
                result = SplitStringsArray(2)
                result = result.Replace("""", "")
            End If
    
            MaxRows = ds2.Tables("CustDetail").Rows.Count
            MaxRows = MaxRows - 1
            Dim numbers() As Integer
            Dim EndAt As Integer
            inc = 0
            EndAt = MaxRows
            ReDim numbers(EndAt)
            For n = inc To EndAt - 1
                If result = result Then
                    'UPDATE THE ALARMSHISTORY table first
                    dsNewRow.Item("TimeStamp") = System.DateTime.Now
                    dsNewRow.Item("CustName") = ds2.Tables("CustDetail").Rows(n).Item("CustName")
                    dsNewRow.Item("BlkName") = ds2.Tables("CustDetail").Rows(n).Item("BlkName")
                    dsNewRow.Item("UnitNum") = ds2.Tables("CustDetail").Rows(n).Item("UnitNum")
                    dsNewRow.Item("EmerNum") = ds2.Tables("CustDetail").Rows(n).Item("EmerNum")
                    dsNewRow.Item("RmuNum") = result
                    dsNewRow.Item("AlarmsMessage") = "Fire alert"
                    'ds.Tables("AlarmHistory").Rows.Add(dsNewRow)
                    da.Update(ds, "AlarmHistory")
                End If
            Next n
    
    
            If (receivedData.IndexOf("Fire alert") <> -1) Then
    
                'intruder alert alarm
                'smoke alarm
    
                'Dim InputString As String = "+CMGL: 1" & "," & "REC READ" & "," & "+6596231118" & "," & "," & "09/08/13,00:17:11+32"
    
    
                MaxRows = ds2.Tables("CustDetail").Rows.Count
                MaxRows = MaxRows - 1
                ' Dim numbers() As Integer
                ' Dim EndAt As Integer
                inc = 0
                EndAt = MaxRows
                ReDim numbers(EndAt)
                For n = inc To EndAt - 1
                    If result = ds2.Tables("CustDetail").Rows(n).Item("RmuNum") Then
                        'UPDATE THE ALARMSHISTORY table first
                        dsNewRow.Item("TimeStamp") = System.DateTime.Now
                        dsNewRow.Item("CustName") = ds2.Tables("CustDetail").Rows(n).Item("CustName")
                        dsNewRow.Item("BlkName") = ds2.Tables("CustDetail").Rows(n).Item("BlkName")
                        dsNewRow.Item("UnitNum") = ds2.Tables("CustDetail").Rows(n).Item("UnitNum")
                        dsNewRow.Item("EmerNum") = ds2.Tables("CustDetail").Rows(n).Item("EmerNum")
                        dsNewRow.Item("RmuNum") = result
                        dsNewRow.Item("AlarmsMessage") = "Fire alert"
                        ds.Tables("AlarmHistory").Rows.Add(dsNewRow)
                        da.Update(ds, "AlarmHistory")
                    End If
                Next n
    
    
    
                'blk1
                conn.Open()
                Dim loginCommand As SqlCommand = conn.CreateCommand()
                loginCommand.CommandText = "SELECT * FROM CustDetail WHERE RmuNum = '" & result & "'" & "AND BlkName LIKE'%01%'"
                Dim dr As SqlDataReader = loginCommand.ExecuteReader
    
                If dr.Read Then
    
                    MaxRows = ds2.Tables("CustDetail").Rows.Count
                    MaxRows = MaxRows - 1
                    ' Dim numbers() As Integer
                    '  Dim EndAt As Integer
                    inc = 0
                    EndAt = MaxRows
                    ReDim numbers(EndAt)
                    For n = inc To EndAt - 1
    
                        If result = ds2.Tables("CustDetail").Rows(n).Item("RmuNum") Then
    
                            Label6.Text = ds2.Tables("CustDetail").Rows(n).Item("CustName")
                            Label8.Text = ds2.Tables("CustDetail").Rows(n).Item("BlkName")
                            Label10.Text = ds2.Tables("CustDetail").Rows(n).Item("UnitNum")
                            Label9.Text = ds2.Tables("CustDetail").Rows(n).Item("EmerNum")
    
                            Dim SplitStringsArray2() As String = receivedData.Split(Convert.ToChar(","))
    
                            Dim result2 As String = String.Empty
                            If SplitStringsArray.GetUpperBound(0) >= 2 Then
                                result2 = SplitStringsArray(0)
                                result2 = result2.Replace("+CMGL:", "")
                                result2 = result2.Trim()
    
                                serialPort.Write("AT+CMGD=" & result2 & vbCrLf)
                            End If
                            Label4.Text = "FIRE ALERT"
                            Label4.Show()
                            Button13.Text = "ACKNOWLEDGE ALARM"
                            Label6.Show()
                            Label8.Show()
                            Label9.Show()
                            Timer2.Enabled = True
                            Timer6.Enabled = True
                            MySoundPlayer.SoundLocation = _
                        "E:\My documents\TP\sem 6 MPSIP\more to project\work from here!!\try out auto read sms\fire alert.wav"
                            MySoundPlayer.Load()
                            MySoundPlayer.Play()
                            Label10.Location = New Point(25, 227)
                            Label10.Show()
                            ' Timer1.Enabled = True
                        End If
                    Next n
                End If
                dr.Close()
                conn.Close()
    
                'blk2
                conn.Open()
                Dim loginCommand2 As SqlCommand = conn.CreateCommand()
                loginCommand2.CommandText = "SELECT * FROM CustDetail WHERE RmuNum = '" & result & "'" & "AND BlkName LIKE'%02%'"
                Dim dr2 As SqlDataReader = loginCommand2.ExecuteReader
    
                If dr2.Read Then
    
                    MaxRows = ds2.Tables("CustDetail").Rows.Count
                    MaxRows = MaxRows - 1
                    ' Dim numbers() As Integer
                    '  Dim EndAt As Integer
                    inc = 0
                    EndAt = MaxRows
                    ReDim numbers(EndAt)
                    For n = inc To EndAt - 1
    
                        If result = ds2.Tables("CustDetail").Rows(n).Item("RmuNum") Then
    
                            Label6.Text = ds2.Tables("CustDetail").Rows(n).Item("CustName")
                            Label8.Text = ds2.Tables("CustDetail").Rows(n).Item("BlkName")
                            Label10.Text = ds2.Tables("CustDetail").Rows(n).Item("UnitNum")
                            Label9.Text = ds2.Tables("CustDetail").Rows(n).Item("EmerNum")
    
                            Dim SplitStringsArray2() As String = receivedData.Split(Convert.ToChar(","))
    
                            Dim result2 As String = String.Empty
                            If SplitStringsArray.GetUpperBound(0) >= 2 Then
                                result2 = SplitStringsArray(0)
                                result2 = result2.Replace("+CMGL:", "")
                                result2 = result2.Trim()
    
                                serialPort.Write("AT+CMGD=" & result2 & vbCrLf)
                            End If
    
    
    
    
                            Label4.Text = "FIRE ALERT"
                            Label4.Show()
                            Button13.Text = "ACKNOWLEDGE ALARM"
                            Label6.Show()
                            Label8.Show()
                            Label9.Show()
                            Timer3.Enabled = True
                            Timer6.Enabled = True
                            MySoundPlayer.SoundLocation = _
                        "E:\My documents\TP\sem 6 MPSIP\more to project\work from here!!\try out auto read sms\fire alert.wav"
                            MySoundPlayer.Load()
                            MySoundPlayer.Play()
                            Label10.Location = New Point(25, 227)
                            Label10.Show()
                            ' Timer1.Enabled = True
                        End If
                    Next n
                End If
                dr2.Close()
                conn.Close()
    
    
                'blk3
                conn.Open()
                Dim loginCommand3 As SqlCommand = conn.CreateCommand()
                loginCommand3.CommandText = "SELECT * FROM CustDetail WHERE RmuNum = '" & result & "'" & "AND BlkName LIKE'%03%'"
                Dim dr3 As SqlDataReader = loginCommand3.ExecuteReader
    
                If dr3.Read Then
    
                    MaxRows = ds2.Tables("CustDetail").Rows.Count
                    MaxRows = MaxRows - 1
                    ' Dim numbers() As Integer
                    '  Dim EndAt As Integer
                    inc = 0
                    EndAt = MaxRows
                    ReDim numbers(EndAt)
                    For n = inc To EndAt - 1
    
                        If result = ds2.Tables("CustDetail").Rows(n).Item("RmuNum") Then
    
                            Label6.Text = ds2.Tables("CustDetail").Rows(n).Item("CustName")
                            Label8.Text = ds2.Tables("CustDetail").Rows(n).Item("BlkName")
                            Label10.Text = ds2.Tables("CustDetail").Rows(n).Item("UnitNum")
                            Label9.Text = ds2.Tables("CustDetail").Rows(n).Item("EmerNum")
    
    
                            Dim SplitStringsArray2() As String = receivedData.Split(Convert.ToChar(","))
    
                            Dim result2 As String = String.Empty
                            If SplitStringsArray.GetUpperBound(0) >= 2 Then
                                result2 = SplitStringsArray(0)
                                result2 = result2.Replace("+CMGL:", "")
                                result2 = result2.Trim()
    
                                serialPort.Write("AT+CMGD=" & result2 & vbCrLf)
                            End If
                            Label4.Text = "FIRE ALERT"
                            Label4.Show()
                            Button13.Text = "ACKNOWLEDGE ALARM"
                            Label6.Show()
                            Label8.Show()
                            Label9.Show()
                            Timer4.Enabled = True
                            Timer6.Enabled = True
                            MySoundPlayer.SoundLocation = _
                        "E:\My documents\TP\sem 6 MPSIP\more to project\work from here!!\try out auto read sms\fire alert.wav"
                            MySoundPlayer.Load()
                            MySoundPlayer.Play()
                            Label10.Location = New Point(25, 227)
                            Label10.Show()
                            ' Timer1.Enabled = True
                        End If
                    Next n
                End If
                dr3.Close()
                conn.Close()
    
                'blk4
                conn.Open()
                Dim loginCommand4 As SqlCommand = conn.CreateCommand()
                loginCommand4.CommandText = "SELECT * FROM CustDetail WHERE RmuNum = '" & result & "'" & "AND BlkName LIKE'%04%'"
                Dim dr4 As SqlDataReader = loginCommand4.ExecuteReader
    
                If dr4.Read Then
    
                    MaxRows = ds2.Tables("CustDetail").Rows.Count
                    MaxRows = MaxRows - 1
                    ' Dim numbers() As Integer
                    '  Dim EndAt As Integer
                    inc = 0
                    EndAt = MaxRows
                    ReDim numbers(EndAt)
                    For n = inc To EndAt - 1
    
                        If result = ds2.Tables("CustDetail").Rows(n).Item("RmuNum") Then
    
                            Label6.Text = ds2.Tables("CustDetail").Rows(n).Item("CustName")
                            Label8.Text = ds2.Tables("CustDetail").Rows(n).Item("BlkName")
                            Label10.Text = ds2.Tables("CustDetail").Rows(n).Item("UnitNum")
                            Label9.Text = ds2.Tables("CustDetail").Rows(n).Item("EmerNum")
    
                            Dim SplitStringsArray2() As String = receivedData.Split(Convert.ToChar(","))
    
                            Dim result2 As String = String.Empty
                            If SplitStringsArray.GetUpperBound(0) >= 2 Then
                                result2 = SplitStringsArray(0)
                                result2 = result2.Replace("+CMGL:", "")
                                result2 = result2.Trim()
    
                                serialPort.Write("AT+CMGD=" & result2 & vbCrLf)
                            End If
    
                            Label4.Text = "FIRE ALERT"
                            Label4.Show()
                            Button13.Text = "ACKNOWLEDGE ALARM"
                            Label6.Show()
                            Label8.Show()
                            Label9.Show()
                            Timer5.Enabled = True
                            Timer6.Enabled = True
                            MySoundPlayer.SoundLocation = _
                        "E:\My documents\TP\sem 6 MPSIP\more to project\work from here!!\try out auto read sms\fire alert.wav"
                            MySoundPlayer.Load()
                            MySoundPlayer.Play()
                            Label10.Location = New Point(25, 227)
                            Label10.Show()
                            ' Timer1.Enabled = True
                        End If
                    Next n
                End If
                dr4.Close()
                conn.Close()
            End If
        End Sub
    
    
       
        '---Event handler for the DataReceived event---
        Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialPort.DataReceived
            MsgBox("DELEGATE")
            Me.BeginInvoke(New myDelegate(AddressOf ReceivedSMS), New Object() {})
    
        End Sub
    
    
        '---Delegate and subroutine to update the TextBox control---
        '---In order to update the form i have to put me.begininvolke---
        Public Delegate Sub myDelegate()
        Public Sub ReceivedSMS()
    
            '---append the received data into the TextBox control---
            ' With txtDataReceived
            '.AppendText(serialPort.ReadExisting)
            ' .ScrollToCaret()
            ' End With
    
        End Sub
    
        Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
            MySoundPlayer.Stop()
    
            Label4.Hide()
    
            Button5.BackColor = Color.Lime
            Button6.BackColor = Color.Lime
            Button7.BackColor = Color.Lime
            Button8.BackColor = Color.Lime
            Button13.Text = "ALARM IDLE"
    
    
            Timer2.Stop()
            Timer3.Stop()
            Timer4.Stop()
            Timer5.Stop()
            Timer6.Stop()
            Timer7.Stop()
            Timer8.Stop()
    
            Label6.Hide()
    
            Label8.Hide()
            Label9.Hide()
            Label10.Hide()
    
        End Sub
    
        Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
    
            Timer2.Start()
    
            If Button5.BackColor = Color.Red Then
                Button5.BackColor = Color.Lime
            Else
                Button5.BackColor = Color.Red
            End If
        End Sub
    
        Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer3.Tick
            Timer3.Start()
    
            If Button6.BackColor = Color.Red Then
                Button6.BackColor = Color.Lime
            Else
                Button6.BackColor = Color.Red
            End If
    
        End Sub
    
        Private Sub Timer4_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer4.Tick
    
            Timer4.Start()
    
            If Button7.BackColor = Color.Red Then
                Button7.BackColor = Color.Lime
            Else
                Button7.BackColor = Color.Red
            End If
    
    
    
    
    
        End Sub
    
    
    
        Private Sub Timer5_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer5.Tick
    
            Timer5.Start()
    
            If Button8.BackColor = Color.Red Then
                Button8.BackColor = Color.Lime
            Else
                Button8.BackColor = Color.Red
            End If
    
    
    
        End Sub
    
        Private Sub Timer6_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer6.Tick
            MySoundPlayer.SoundLocation = _
            "E:\My documents\TP\sem 6 MPSIP\more to project\work from here!!\try out auto read sms\fire alert.wav"
            MySoundPlayer.Load()
            MySoundPlayer.Play()
    
        End Sub
    
        Private Sub Timer7_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer7.Tick
    
            MySoundPlayer.SoundLocation = _
            "F:\My documents\TP\sem 6 MPSIP\more to project\project submission backup file(dont touch)\Auto read incoming sms for submission\burglar_alarm_going_off.wav"
            MySoundPlayer.Load()
            MySoundPlayer.Play()
    
        End Sub
    
        Private Sub Timer8_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer8.Tick
    
            MySoundPlayer.SoundLocation = _
                    "F:\My documents\TP\sem 6 MPSIP\more to project\project submission backup file(dont touch)\Auto read incoming sms for submission\smoke-detector-1.wav"
            MySoundPlayer.Load()
            MySoundPlayer.Play()
    
    
        End Sub
    
    
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            AlarmHistory.Show()
        End Sub
    
        
        
    End Class
    
    regards,
    charles
    Tuesday, August 25, 2009 6:28 AM

All replies

  • Hi Charles,

    Please give out detailed description about your requirement so that we can understand your code and your current requirement.
    Best regards,
    Riquel
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, August 28, 2009 8:16 AM
    Moderator
  • hi,

    well actually i wanted to change to the serial port interrupt method. So what this method does is it will fire the events when ever the serial port buffer is full and do nothing when the serial port buffer is empty. 

    Currently i have my main codes in timer 1 control as i'm actually using the datareceived polling method.

    I read online that i can use the delegate method which is actually called the interrupt method. So i am wondering based on my codes structure, how can i change the coding so that i can change to the delegate method easily.

    hope someone can actually guide me here. Thnks!!

     
    Friday, August 28, 2009 2:17 PM
  • Please give the small online sample to let me know what you want to implement. You just handle the SerialPort. DataReceived event to receive the data. It is OK. Don't use Timer component with this event together.

    Best regards,
    Riquel
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Monday, August 31, 2009 8:53 AM
    Moderator
  • Hi thnks for the reply. Erm my partner just managed to solve the delegate part but we're still testing to see if its working. Will let you know the results.
    Monday, August 31, 2009 3:11 PM