dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Discover a New Frontier for .NET Development: Program an LCD Display : Page 3

Personal computers aren't the only place where applications can run. As we look toward the future, the possibilities are limitless for creating applications that manipulate other types of displays. Get started with this sample .NET application that controls an LCD display.


advertisement
Clear Display
To clear the LCD display, call the ClearDisplay() method of the LCD class:

    Private Sub btnClearDisplay_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnClearDisplay.Click
        LCD_Display.ClearDisplay()
    End Sub
Custom Characters
To define a custom character, first initialize the byte array for the character and then call the DefineCustomChar() method of the LCD class.

    Private Sub btnCustomChar_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnCustomChar.Click

        Dim bytes(7) As Byte
        bytes(0) = &H0
        bytes(1) = &HA
        bytes(2) = &HA
        bytes(3) = &H0
        bytes(4) = &H11
        bytes(5) = &HE
        bytes(6) = &H6
        bytes(7) = &H0

        '---defines the custom character---
        LCD_Display.DefineCustomChar(CustomChar.ch0, bytes)

        '---display the custom char at a specific location---
        LCD_Display.SetCursorPosition(4, 15)
        LCD_Display.WriteCustomChar(CustomChar.ch0)
    End Sub
To test that the custom character is defined correctly, you will write the custom character at a specified location. These two tasks are accomplished by the WriteCustomChar() and SetCursorPosition() methods, respectively.

Display CPU Usage Graph
You can obtain the CPU utilization using WMI (Windows Management Instrumentation). Using WMI, you can obtain detailed information about your hardware and devices. The Display_CPU_Usage() subroutine repeatedly queries the CPU utilization rate and then updates the graph:


    '---display CPU usage using a graph---
    Public Sub Display_CPU_Usage()
        LCD_Display.ClearDisplay()
        LCD_Display.InitThickVerticalBarGraph()
        Dim oQ As ObjectQuery = _
           New ObjectQuery("select * from Win32_Processor")
        Dim searcher As ManagementObjectSearcher = _
           New ManagementObjectSearcher(oQ)
        While True
            For Each CPU As ManagementObject In searcher.Get()
                LCD_Display.DrawBarGraph(CPU("LoadPercentage"))
                Exit For '---skip the next processor---
            Next
        End While
    End Sub
Notice that in the For Each loop, I have inserted an Exit For statement. This is because I am testing this application on a dual core CPU, and in this case I am only interested in the CPU utilization of the first processor.

Author's Note: You need to add the System.Management DLL to the project for WMI to work.

As the Display_CPU_Usage() subroutine runs in an infinite loop, you should not call the function directly from the event hander of the button as this will freeze the UI. Instead, use a separate thread to call it:


    Private Sub btnCPUUsage_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnCPUUsage.Click
        t1 = New Thread(AddressOf Display_CPU_Usage)
        t1.Start()
    End Sub
Display RSS Feeds
One good use of the LCD display is to display headlines from an RSS feed. The Display_RSS() subroutine retrieves a RSS document and then displays the title of each post on the LCD:

    '---display RSS feeds---
    Private Sub Display_RSS()
        Dim req As HttpWebRequest
        Dim xmlDoc As XmlDocument = Nothing
        Try
            LCD_Display.ClearDisplay()
            '---download the RSS document---
            req = _
        SendRequest("http://services.devx.com/outgoing/devxfeed.xml", _
        "GET")
            Dim xmlData As String = GetResponse(req)
            xmlDoc = New XmlDocument()
            xmlDoc.LoadXml(xmlData)
            '---Select the title of the document---
            Dim titlesNode As XmlNodeList = _
               xmlDoc.DocumentElement.SelectNodes("channel/item/title")
            For i As Integer = 0 To titlesNode.Count - 1
                LCD_Display.Write("* " & _
                   titlesNode(i).InnerText.ToString(), True)
                LCD_Display.Write(vbCrLf & vbCrLf, True)
            Next
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
The two supporting functions used by the Display_RSS() subroutine are defined below:

    Public Function SendRequest( _
        ByVal URI As String, _
        ByVal requestType As String) As HttpWebRequest
        Dim req As HttpWebRequest = Nothing
        Try
            '---Creates a HTTP request---
            req = HttpWebRequest.Create(URI)
            req.Method = requestType '---GET or POST---
        Catch ex As Exception
            Throw New Exception("Error")
        End Try
        Return req
    End Function

    Public Function GetResponse( _
       ByVal req As HttpWebRequest) As String
        Dim body As String = String.Empty
        Try
            '---Get a response from server---
            Dim resp As HttpWebResponse = req.GetResponse()
            Dim stream As Stream = resp.GetResponseStream()
            '---Use a StreamReader to read the response---
            Dim reader As StreamReader = _
               New StreamReader(stream, System.Text.Encoding.UTF8)
            body = reader.ReadToEnd()
            stream.Close()
        Catch ex As Exception
            Throw New Exception("Error")
        End Try
        Return body
    End Function
To ensure that displaying the RSS feed does not freeze up the UI, use a thread to invoke it:

    Private Sub btnDisplayRSS_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnDisplayRSS.Click
        t2 = New Thread(AddressOf Display_RSS)
        t2.Start()
    End Sub
Display Time
The LK204-25 supports large digits and this is useful for displaying information such as time. The Display_Time() subroutine continuously displays the current time and updates it every one second (1000 milliseconds):

    '---display the current time---
    Public Sub Display_Time()
        LCD_Display.BlockCursorONOFF(False)
        LCD_Display.ClearDisplay()
        LCD_Display.InitLargeDigits()
        While True
            Dim hour, minute, second As String
            hour = Now.Hour.ToString("0#")
            minute = Now.Minute.ToString("0#")
            second = Now.Second.ToString("0#")

            '---display the hour---
            LCD_Display.PlaceLargeDigits(1, CInt(hour(0).ToString))
            LCD_Display.PlaceLargeDigits(4, CInt(hour(1).ToString))

            '---display the minute---
            LCD_Display.PlaceLargeDigits(8, CInt(minute(0).ToString))
            LCD_Display.PlaceLargeDigits(11, CInt(minute(1).ToString))

            '---display the second---
            LCD_Display.PlaceLargeDigits(15, CInt(second(0).ToString))
            LCD_Display.PlaceLargeDigits(18, CInt(second(1).ToString))

            Thread.Sleep(1000)
        End While
    End Sub
As usual, to avoid freezing the UI, you should call the subroutine using a separate thread:

    Private Sub btnDisplayTime_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnDisplayTime.Click
        t3 = New Thread(AddressOf Display_Time)
        t3.Start()
    End Sub
Read Version Number
You can read the firmware version number of the LK204-25 by sending the appropriate command to it. This is a good chance to demonstrate how to read data sent from the LCD display. The is accomplished by the ReadVerNumber() method of the LCD class:

    Private Sub btnReadVersionNum_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnReadVersionNum.Click
        LCD_Display.ReadVerNumber()
    End Sub
When data is received, the DataFromLCDDisplay event handler will fire:

    '---when data is received from the LCD---
    Public Sub DataFromLCDDisplay( _
       ByVal str As String) Handles LCD_Display.DataFromLCD
        MsgBox(str)
    End Sub
Author's Note: For some unknown reason, my LCD display always returns a "T" when queried about its firmware information.

Set the Contrast and Turn On/Off the Backlight
You can set the contrast of the LCD by moving the TrackBar control:


    Private Sub TrackBar1_Scroll( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles TrackBar1.Scroll
        LCD_Display.SetContrast(TrackBar1.Value)
    End Sub
To turn on/off the backlight of the LK204-25, check (or uncheck) the chkBacklight control:

    Private Sub chkBacklight_CheckedChanged( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles chkBacklight.CheckedChanged

        If Not FormLoaded Then Exit Sub
        If chkBacklight.Checked Then
            LCD_Display.BackLightON(0)
        Else
            LCD_Display.BackLightOFF()
        End If
    End Sub
Stopping the Threads
To stop the threads running the various functions, code the three Stop buttons as follows:

    Private Sub btnStopCPUUsage_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnStopCPUUsage.Click
        t1.Abort()
    End Sub

    Private Sub btnStopRSSFeeds_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnStopRSSFeeds.Click
        t2.Abort()
    End Sub

    Private Sub btnStopDisplayTime_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnStopDisplayTime.Click
        t3.Abort()
    End Sub
Testing the Application
Finally, you are now ready to test the LCD. Press F5 to debug the application. Ensure that your serial cable is connected to both the PC and the LCD. Click on the various buttons and observe the output on the screen. You can also view the following videos to see it in action.

The videos show, from left to right, the Timer function, the CPU Usage function, and the Display RSS feeds function. Click each Play button twice to start the video.

In this article, you have seen how you can easily connect an external device such as a LCD display to your computer. More importantly, you have learnt how to use .NET to communicate with these devices, and in this particular case, how the SerialPort class is put into action. I hope you have fun with this project; send me your ideas for using the LCD display! In future articles on DevX I will help you expand the skills learned here to interface .NET applications with external devices in other ways.



Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.
Thanks for your registration, follow us on our social networks to keep up-to-date