devxlogo

Infrared Programming Using the .NET Compact Framework

Infrared Programming Using the .NET Compact Framework

nfrared communication is one of the most common forms of communication for devices today. If you’ve ever used a TV remote control, you’ve experienced the convenience of using infrared communications. While infrared communications require line-of-sight between the sending and receiving devices, they are a quick and cheap way of communicating between devices.

Most Windows Mobile devices you buy today come with an infrared port, but latley it seems like Bluetooth has been taking the limelight because it has a wider operating radius and most importantly it does not require line-of-sight in order to work. Despite this limitation, infrared requires no pairing of devices, and certainly does not require the hassles of exchanging secret pin numbers. For this reason, it is quite suitable for applications that require fast exchanges of information. For example, site surveyors may use Windows Mobile devices for taking photos, and at the end of the day they can simply transfer the images to a PC using infrared.

This article shows you how you can use infrared to communicate between a Windows Mobile device and a PC.

What You Need
  • The System.Net.IrDA library, available in the .NET Compact Framework
  • The 32feet.NET library, available here.
  • An infrared USB adapter

Infrared Programming on Windows Mobile and PC
Using infrared on Windows Mobile Pocket PCs is easy using the System.Net.IrDA library, available in the .NET Compact Framework. What about using infrared on the desktop PC? Unfortunately, the .NET Framework does not come with the System.Net.IrDA library, which means you cannot use infrared using the .NET Framework directly. To do so, you’ll need the 32feet.NET library,written by fellow MVP, Peter Foot (http://www.peterfoot.net/). This library makes infrared programming available to managed developers. 32feet.NET is a project that aims to make wireless networking (via Bluetooth and IrDA) much more easily accessible from .NET code, whether it’s on mobile devices or desktop computers. You can download the latest version of 32feet.NET (v2.0.60828) from here.

In this article, you’ll build two applications?one for the Windows Mobile 5.0 Pocket PC and one for the desktop. The Pocket PC application allows users to transfer images to the desktop using infrared.

Building the Pocket PC Application
First, let’s build the Pocket PC application that allows users to send an image to the desktop using infrared.

Using Visual Studio 2005, create a new Windows Mobile 5.0 Pocket PC application and name it Infrared. Populate the default Form1 with the following controls (see Figure 1):

  • Button
  • PictureBox
  • StatusBar
  • MenuItem
  • Figure 1. Form1: Populated with the various controls.

    Next, add a reference to the System.Net.IrDa library.

    Switch to the code-behind of Form1 and import the following namespaces:

Imports System.NetImports System.IOImports System.Net.Sockets

Define the following constants and member variable:

Public Class Form1    '---define the constants---    Const DATA_BLOCK_SIZE As Integer = 8192    Const MAX_TRIES As Integer = 3    Private ServiceName As String = "default"

The DATA_BLOCK_SIZE constant is the maximum size of data exchanged, and MAX_TRIES is the maximum number of tries to send a block of data before giving up. The ServiceName variable is a unique identifier used by the two communicating parties participating in an infrared communication session.

Code the "Select image to send? button as follows:    Private Sub btnSelectImage_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles btnSelectImage.Click        Dim openFileDialog1 As New OpenFileDialog()        openFileDialog1.Filter = "JPEG files (*.jpg)|*.jpg"        If openFileDialog1.ShowDialog() = _           DialogResult.OK Then            '---load the PictueBox control with the select image---            PictureBox1.Image = New Bitmap(openFileDialog1.FileName)        End If    End Sub

The above code basically displays the Open File dialog that allows users to select a .jpg image. Once the image is selected, it is displayed in the PictureBox control.

Next, define the SendData() subroutine, which sends the image to the PC over an infrared connection (shown in Listing 1).

First, the SendData() subroutine tries to establish a connection with the other device (using the IrDAClient class) until the number of retries is exceeded. Once a connection is established, it writes to the other device using an IO Stream object. Finally, it closes the stream and the connection.

Define the UpdateStatus() subroutine and its delegate as follows:

    Private Delegate Sub myDelegate(ByVal str As String)    Private Sub UpdateStatus(ByVal str As String)        '---delegate to update the statusbar control        StatusBar1.Text = str    End Sub

Finally, code the Send menu item as follows:

The mnuSend_Click event handler first converts the image in the PictureBox control into a byte array and then sends it to the PC by calling the SendData() subroutine, defined earlier in Listing 1.

Building the PC Application
With the Pocket PC application built, you can now build the PC application that listens for incoming infrared data.

Using Visual Studio 2005, create a new Windows application and name it Infrared_Desktop. Populate the default Form with the PictureBox control (see Figure 2).

Figure 2. Form1: Populated with the PictureBox control.

Add a reference to the InTheHand.Net.Personal library.

Switch to the code-behind of Form1 and import the following namespaces:

Imports System.IOImports System.Net.SocketsImports InTheHand.Net.SocketsAs usual, define the following constants and member variable:Public Class Form1    '---define the constants---    Const DATA_BLOCK_SIZE As Integer = 8192    Const MAX_TRIES As Integer = 3    Private ServiceName As String = "default"

Define the ReceiveData() function so that it can receive incoming infrared data (shown in Listing 2).

You use the IrDAListener class to listen for an IrDa connection. Once a connection is established, you read the incoming data using a Stream object. Because incoming data may not be read in one go, you will repeatedly read from the stream until no more data is available. The function returns the data received as a byte array.

Next, define the ReceiveLoop() subroutine that calls the ReceiveData() function in a infinite loop:

    Public Sub ReceiveLoop()        Dim dataReceived As Byte()        '---listen for incoming data---        dataReceived = ReceiveData()        While True            If DataReceived.Length > 0 Then                PictureBox1.BeginInvoke( _                   New myDelegate(AddressOf DisplayImage), _                   New Object() {dataReceived})            End If            '---keep on listening for incoming data---            dataReceived = ReceiveData()        End While    End Sub

Define the DisplayImage() subroutine and its delegate as follows:

    Private Delegate Sub myDelegate(ByVal data As Byte())    Private Sub DisplayImage(ByVal data As Byte())        Try            Dim ms As MemoryStream = New MemoryStream(data)            PictureBox1.Image = New Bitmap(Image.FromStream(ms))        Catch ex As Exception            MsgBox(ex.ToString)        End Try    End Sub

The DisplayImage() subroutine converts the received byte array into an image so that it can be displayed by the PictureBox control.

Finally, when the form is loaded, invoke the ReceiveLoop() subroutine using a thread so that it can listen for incoming data in the background:

    Private Sub Form1_Load( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles MyBase.Load        '---receive incoming data as a separate thread---        Dim t1 As System.Threading.Thread        t1 = New Threading.Thread(AddressOf ReceiveLoop)        t1.Start()    End Sub

Testing the Application
Now, you can test the two applications. First, you need to ensure that your PC has an infrared port. If not, you can use an infrared USB adapter, which can be purchased for less than $10.00.

Figure 3. Action! Testing the two applications.

Run the Infrared_Desktop application first and then deploy the IrDA application to your Windows Mobile 5.0 Pocket PC. Align the infrared port on the Pocket PC with the port on your PC. On the Pocket PC, click the “Select image to send” button to select an image. Then, click the Send button to send the image over to the PC. Figure 3 shows the Pocket PC and PC applications in action.

Quick and Easy
See how easy it is to exchange data between a Pocket PC and a PC using infrared? Infrared is well suited for applications that require a quick and easy way to exchange data, all without the burden of asking the user to perform a series of complicated steps.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist