Search This Blog

Tuesday, March 23, 2010

VB.net code send/receive a byte from atmega16 microcontroller

VB.net code send/receive a byte from atmega16 microcontroller, serially.
 Form has some button to send a byte.
---------------------------------------------------------------------------

Option Explicit On
Option Strict On
Imports System.IO.Ports
Imports System.Threading


Public Class Form1
    Dim WithEvents btn As SerialPort
    Dim thRec As Thread
    Dim a As Integer
    Dim b As Byte
    Dim myComPort As New SerialPort
    Dim xmtBuf() As Byte = {&HFF, &H1, &HC3, &HE3, &HFF, &HFF}
    Dim msg(5) As Byte '= New Byte(1) {}
    '''
    ''' Call a routine to write a command to turn off an LED and read the response.
    '''

    '''
    Private Sub btnOff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOff.Click
        If SerialPort1.IsOpen Then
            CloseComPort()
        End If
        Me.Close()


    End Sub

    '''
    ''' Call a routint write a command to turn on an LED and read the response.
    '''

    '''


    '''
    ''' If myComPort is open, finish transmitting.
    ''' Exiting the Using block closes the port and releases its resources.
    '''

    '''
    Sub CloseComPort()

        Try
            Using SerialPort1
                If (Not (SerialPort1 Is Nothing)) Then
                    ' The COM port exists.

                    If SerialPort1.IsOpen Then

                        ' Wait for the transmit buffer to empty.

                        Do While (SerialPort1.BytesToWrite > 0)
                        Loop

                    End If
                End If

            End Using

        Catch ex As UnauthorizedAccessException

            ' The port may have been removed. Ignore.

        End Try

    End Sub

    '''
    ''' Set the BaudRate property of myComPort to match the bit rate selected in the combo box.
    '''

    '''
    Private Sub cmbBitRate_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBitRate.SelectedIndexChanged

        SerialPort1.BaudRate = CInt(cmbBitRate.SelectedItem)

    End Sub

    '''
    ''' If the previously selected COM port is open, close it.
    ''' Set the PortName property of myComPort to match the port selected in the combo box.
    ''' Call a routine to open the port.
    '''

    '''
    Private Sub cmbPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPorts.SelectedIndexChanged


    End Sub

    '''
    ''' Call a routine to close the COM port.
    '''


    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        CloseComPort()

    End Sub

    '''
    ''' Call routines to initalize the form and open the selected COM port.
    '''

    '''
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        InitializeForm()
        ' OpenComPort()

    End Sub

    '''
    ''' Set up the form and select a default port and bit rate.
    '''


    Sub InitializeForm()

        Dim bitRates(9) As Integer
        Dim nameArray() As String

        ' Find the COM ports on the system.

        nameArray = SerialPort.GetPortNames
        Array.Sort(nameArray)

        ' Fill a combo box with the port names.

        cmbPorts.DataSource = nameArray
        cmbPorts.DropDownStyle = ComboBoxStyle.DropDownList

        ' Select a default port.

        cmbPorts.SelectedIndex = 1

        'Bit rates to select from.

        bitRates(0) = 300
        bitRates(1) = 600
        bitRates(2) = 1200
        bitRates(3) = 2400
        bitRates(4) = 9600
        bitRates(5) = 14400
        bitRates(6) = 19200
        bitRates(7) = 38400
        bitRates(8) = 57600
        bitRates(9) = 115200

        'Place the bit rates in a combo box.

        cmbBitRate.DataSource = bitRates
        cmbBitRate.DropDownStyle = ComboBoxStyle.DropDownList

        ' Select a default bit rate.

        cmbBitRate.SelectedItem = 9600

    End Sub

    '''
    ''' Set port parameters and open the COM port
    ''' associated with the SerialPort object myComPort.
    '''


    Sub OpenComPort()

        Try
            ' Get the selected COM port's name from the combo box.

            If Not SerialPort1.IsOpen Then
                SerialPort1.PortName = cmbPorts.SelectedItem.ToString
                ' myComPort.PortName = "com3"
                ' Get the selected bit rate from the combo box.

                If cmbBitRate.SelectedIndex > 0 Then
                    SerialPort1.BaudRate = CInt(cmbBitRate.SelectedItem)
                End If

                ' Set other port parameters.
                SerialPort1.BaudRate = 4800 'CInt(cmbBitRate.SelectedItem) '9600
                SerialPort1.Parity = Parity.None
                SerialPort1.DataBits = 8
                SerialPort1.StopBits = StopBits.One
                SerialPort1.Handshake = Handshake.None
                SerialPort1.WriteBufferSize = 100000

                SerialPort1.DtrEnable = True
                SerialPort1.RtsEnable = True
                ' Open the port.

                SerialPort1.Open()

                'MessageBox.Show("opened")
            End If

        Catch ex As InvalidOperationException
            MessageBox.Show(ex.Message)

        Catch ex As UnauthorizedAccessException
            MessageBox.Show(ex.Message)

        Catch ex As System.IO.IOException
            MessageBox.Show(ex.Message)

        End Try

        btnOn.Enabled = True
        Button1.Enabled = True
        Button2.Enabled = True
    End Sub

    '''
    ''' Write a command to the SerialPort object and read the response.
    '''

    '''
The command to send.

    Private Sub SendCommand(ByVal command As String)

        Dim response As String
        Dim a As Integer
        Try

            'myComPort.Write("V")
            'myComPort.WriteLine("1")

            SerialPort1.WriteLine("255")

            'a = myComPort.r
            'TextBox1.Text = (Asc(myComPort.ReadLine).ToString)
            Select Case response

                Case "0"

                    lblStatus.Text = "LED 1 is OFF"

                Case "1"

                    lblStatus.Text = "LED 1 is ON"

                Case Else

            End Select

        Catch ex As TimeoutException
            MessageBox.Show(ex.Message)

        Catch ex As InvalidOperationException
            MessageBox.Show(ex.Message)

        Catch ex As UnauthorizedAccessException
            MessageBox.Show(ex.Message)

        End Try
    End Sub

    'Private Sub myComPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles myComPort.DataReceived


    '    MessageBox.Show(myComPort.ReadExisting().ToString)
    'End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try

            'myComPort.Write("V")
            SerialPort1.WriteLine("254")
            'a = myComPort.r
            ' TextBox1.Text = (Asc(myComPort.ReadLine).ToString)


        Catch ex As TimeoutException
            MessageBox.Show(ex.Message)

        Catch ex As InvalidOperationException
            MessageBox.Show(ex.Message)

        Catch ex As UnauthorizedAccessException
            MessageBox.Show(ex.Message)

        End Try
    End Sub


    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try

            'b = CType(TextBox2.Text, Byte)
            ' b = HexToByte(TextBox2.Text)
            ' b = Hex(CType(TextBox2.Text, Integer))
            'myComPort.WriteLine(a.ToString)
            'myComPort.Write(b, 0, 1)


            TextBox1.Text = Hex(CType(TextBox2.Text, Integer)).ToString
            If CType(TextBox2.Text, Integer) = 255 Then
                msg(0) = &HFF
            ElseIf CType(TextBox2.Text, Integer) = 254 Then
                msg(0) = &HFE
            ElseIf CType(TextBox2.Text, Integer) = 253 Then
                msg(0) = &HFD
            ElseIf CType(TextBox2.Text, Integer) = 252 Then
                msg(0) = &HFC
            ElseIf CType(TextBox2.Text, Integer) = 251 Then
                msg(0) = &HFB
            ElseIf CType(TextBox2.Text, Integer) = 250 Then
                msg(0) = &HFA
            Else
                msg(0) = &H0
            End If
            'Do While (myComPort.BytesToWrite > 0)
            'Loop

            msg(0) = CType(70, Byte)

            msg(1) = CType(71, Byte)

            msg(2) = CType(72, Byte)

            msg(3) = CType(73, Byte)


            'msg(0) = &HFF
            'msg(1) = &HFE
            'msg(2) = &HFD
            'msg(3) = &HFC
            'msg(4) = &HFB
            'msg(5) = &HFA
            'msg(6) = &H0
            'myComPort.Write(msg, 0, 1)
            SerialPort1.Write(msg, 0, 4)
            'myComPort.Write(msg, 0, 1)

            'myComPort.Write(xmtBuf, 0, xmtBuf.Length)
            'myComPort.WriteLine(a.ToString)
            'a = myComPort.r
            '  TextBox1.Text = (Asc(myComPort.ReadLine).ToString)


        Catch ex As TimeoutException
            MessageBox.Show(ex.Message)

        Catch ex As InvalidOperationException
            MessageBox.Show(ex.Message)

        Catch ex As UnauthorizedAccessException
            MessageBox.Show(ex.Message)

        End Try
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        CloseComPort()
        SerialPort1.PortName = cmbPorts.SelectedItem.ToString
        OpenComPort()
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        TextBox1.Text = Chr(CType(TextBox2.Text, Integer)).ToString

    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        TextBox1.Text = ChrW(CType(TextBox2.Text, Integer)).ToString
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        TextBox1.Text = Hex(CType(TextBox2.Text, Integer)).ToString
    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        TextBox1.Text = Asc(TextBox2.Text).ToString
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Try

            'b = CType(TextBox2.Text, Byte)
            ' b = HexToByte(TextBox2.Text)
            ' b = Hex(CType(TextBox2.Text, Integer))
            'myComPort.WriteLine(a.ToString)
            'myComPort.Write(b, 0, 1)



            TextBox1.Text = Hex(CType(ComboBox1.SelectedItem, Integer)).ToString
            If CType(ComboBox1.SelectedItem, Integer) = 255 Then
                msg(0) = 255
            ElseIf CType(ComboBox1.SelectedItem, Integer) = 254 Then
                msg(0) = 254
            ElseIf CType(ComboBox1.SelectedItem, Integer) = 253 Then
                msg(0) = 253
            ElseIf CType(ComboBox1.SelectedItem, Integer) = 252 Then
                msg(0) = &HFC
            ElseIf CType(ComboBox1.SelectedItem, Integer) = 251 Then
                msg(0) = &HFB
            ElseIf CType(ComboBox1.SelectedItem, Integer) = 250 Then
                msg(0) = &HFA
            Else
                msg(0) = &H0
            End If
            'Do While (myComPort.BytesToWrite > 0)
            'Loop

            'msg(0) = &HFF
            'msg(1) = &HFE
            'msg(2) = &HFD
            'msg(3) = &HFC
            'msg(4) = &HFB
            'msg(5) = &HFA
            'msg(6) = &H0
            SerialPort1.Write(msg, 0, 1)
            SerialPort1.Write(msg, 0, 1)
            '            myComPort.Write(msg, 0, 1)

            'myComPort.Write(xmtBuf, 0, xmtBuf.Length)
            'myComPort.WriteLine(a.ToString)
            'a = myComPort.r
            '  TextBox1.Text = (Asc(myComPort.ReadLine).ToString)


        Catch ex As TimeoutException
            MessageBox.Show(ex.Message)

        Catch ex As InvalidOperationException
            MessageBox.Show(ex.Message)

        Catch ex As UnauthorizedAccessException
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

    End Sub
    Private Sub btnOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOn.Click
        Dim msg As String = SerialPort1.ReadExisting()
        MessageBox.Show(msg)
    End Sub
    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        'This event will Receive the data from the selected COM port..
        MessageBox.Show(SerialPort1.ReadExisting().ToString)
        'If e.EventType = SerialData.Chars Then
        '    thRec = New Thread(AddressOf ReceiveData)
        '    thRec.IsBackground = True
        '    thRec.Priority = ThreadPriority.Highest
        '    thRec.Start()
        '    Thread.Sleep(2)
        'End If
    End Sub
    Private Sub ReceiveData()
        'Sub to Receive Data from the Serial Port, Will Run in a Thread
        MessageBox.Show(SerialPort1.ReadExisting().ToString)
        Dim lstItem As ListViewItem
        Dim bRead, nRead As Integer
        Dim returnStr As String = ""
        Dim ascStr As String = ""
        Dim aa As Char
        bRead = SerialPort1.BytesToRead 'Number of Bytes to read
        Dim cData(bRead - 1) As Byte
        ' SerialPort1.Encoding = System.Encoding.GetEncoding(65001)
        nRead = SerialPort1.Read(cData, 0, bRead)  'Reading the Data
        For Each b As Byte In cData
            ascStr += Chr(b)        'Ascii String
            returnStr += Hex(b).PadLeft(2, aa)     'Hex String (Modified Padding, to intake compulsory 2 chars, mainly in case of 0)
        Next
        MessageBox.Show(returnStr)
    End Sub
    'Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
    '      Handles SerialPort1.DataReceived
    '    MessageBox.Show("data received")
    '    MessageBox.Show(SerialPort1.ReadExisting().ToString)

    '    ' txtDataReceived.Invoke(New updateParameters(AddressOf updateTextBox), New Object() {})
    'End Sub
    'Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
    '    'determine the mode the user selected (binary/string)
    '    'Select Case CurrentTransmissionType
    '    'Case TransmissionType.Text
    '    'user chose string
    '    'read data waiting in the buffer
    '    MessageBox.Show("v")
    '    Dim msg As String = myComPort.ReadExisting()
    '    MessageBox.Show(msg)
    '    'display the data to the user
    '    ' _type = MessageType.Incoming
    '    ' _msg = msg
    '    ' DisplayData(MessageType.Incoming, msg + "" + Environment.NewLine + "")
    '    'Exit Select
    '    '    Case TransmissionType.Hex
    '    'user chose binary
    '    'retrieve number of bytes in the buffer
    '    Dim bytes As Integer = myComPort.BytesToRead
    '    'create a byte array to hold the awaiting data
    '    Dim comBuffer As Byte() = New Byte(bytes - 1) {}
    '    'read the data and store it
    '    myComPort.Read(comBuffer, 0, bytes)
    '    MessageBox.Show(comBuffer.ToString)
    '    'display the data to the user
    '    ' _type = MessageType.Incoming
    '    ' _msg = ByteToHex(comBuffer) + "" + Environment.NewLine + ""
    '    ' DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "" + Environment.NewLine + "")
    '    ' Exit Select
    '    '    Case Else
    '    'read data waiting in the buffer
    '    'Dim str As String = myComPort.ReadExisting()
    '    'display the data to the user
    '    '_type = MessageType.Incoming
    '    '_msg = str + "" + Environment.NewLine + ""
    '    ' DisplayData(MessageType.Incoming, str + "" + Environment.NewLine + "")
    '    ' Exit Select
    '    ' End Select
    'End Sub
End Class

1 comment:

  1. Thank you for the info. It sounds pretty user friendly. I guess I’ll pick one up for fun. thank u




    ASC Coding

    ReplyDelete