Arduino and Windows Phone: Basic Connection

Greetings all. This article will be dealing with Arduino and its control using a Windows Phone. Though I will be explaining this taking the Arduino board as a reference, this technique applies to all other boards including the Intel Galileo.

The following is the hardware required:

 

  1. Arduino board (the Arduino Leonardo is used here).
  2. A Bluetooth module (HC06 is used here).

The following is the software required:

 

  1. Arduino IDE
  2. Microsoft Visual Studio

Level of proficiency

The level of proficiency for this article is intermediate.

My last two articles were completely based on control of Arduino by a WPF app and then I did the same thing but by RF communication. This won't be dealing with a WPF application but use a Windows Phone. Obviously due to its small size and less of hardware required, this is a better option in some way if not all. Well, that's another story.

Introduction to the system

This system is based on Bluetooth connectivity with the Arduino so definitely we will need a Bluetooth module. We will use a HC06 module since my experiments are based on that. However HC05 is a better option for some reasons. We will deal with it later in this article itself. Our main course of action is to establish the communication between the two devices. After establishing the connection, the story is the same. The exchange of characters serially will initiate the execution of commands. Before proceeding, I may ask you to go through my previous article on wireless communication so as to make your concepts clear. Let us begin with the Windows Phone.

Windows Phone app for control

For controlling the Arduino, we need an app that will first establish the connection and then communicate serially using the Bluetooth protocol. Here I am using Windows Phone 8.0.

Note: When starting to work with Bluetooth for Windows Phone 8.0, I encountered many problems, especially when I used the APIs from scratch. Then I came across an article in the Nokia developers group. Unfortunately the website has been deactivated after Microsoft's acquisition of Nokia devices and their services. In the tutorial he used a class that carried out most of the work. The app that we will develop today, will also use the same class. The file can be downloaded from this page.

Before hitting the code, let's first get an idea about what we are actually up to. Windows Phone 8.0 basically can have one of the following two types of scenarios.

 

  1. App to app
  2. App to device

This article will deal with only app to device.

First create a new project in Visual Studio under Windows Phone apps development. Name it powerup. You can name anything though. Now as usual before going into the main code, we need to create a user interface. Our UI will contain the following items:

 

  1. A TextBox named deviceName
  2. A button named connect for connecting to the HC05.
  3. A button named on for switching on the LED.
  4. A button named off for switching off the LED.

Figure 1 contains the screenshot of our app's UI.

Figure 1: Screenshot of our app powerup's UI.

My UIs aren't much up to the standard. But this basic UI will do the job required. Also I introduced the color to remove the gloomy Black color.

Our next course of action is to create click event handlers for our buttons since they will have some specific actions. Just double-click on the buttons and the event handlers will be automatically created. The code shown below is just for the grid control where all the controls are placed. 

  1. <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  2.             <TextBox x:Name="DeviceName" HorizontalAlignment="Left" Height="72" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="217" Margin="10,331,0,0"/>  
  3.             <Button x:Name="on" Content="On" HorizontalAlignment="Left" Margin="178,88,0,0" Grid.Row="1" VerticalAlignment="Top" Click="on_Click"/>  
  4.             <Button Content="Off" HorizontalAlignment="Left" Margin="176,160,0,0" Grid.Row="1" VerticalAlignment="Top" Click="Button_Click"/>  
  5.             <Button x:Name="connect" Content="connect" HorizontalAlignment="Left" Margin="241,331,0,0" Grid.Row="1" VerticalAlignment="Top" Width="161" Click="connect_Click"/>  
  6.         </Grid>  

Well, our UI part is ready. Now we will move to MainPage.xaml.cs but before navigating there, we will add the class that would simplify the entire process. Go to the Solution Explorer and right-click on your project name. Then click on add and then on add new item. Now click on class and provide the name ConnectionManager.cs. This will include the main C# code and we will use this class to simplify the communication process. The downloadable file contains the class. Also we need to add this capability to our VMAppManifest.xaml. 

ID_CAP_PROXIMITY
ID_CAP_NETWORKING

Please note that the code for ConnectionManager.cs is NOT written by me. I got that from an article in the Nokia developer group. The website has been deactivated after Nokia's acquisition by Microsoft.  The name of the developer is Marcos Pereira. You can access his YouTube channel. 
 
Now let us write the code required for communication using ConnectionManager.cs. As specified earlier, the scenario will be app to device. For our app to work, we need to add our HC05 to the paired device. It will be discussed later on. I won't be going into the in-depth level of Bluetooth communication. Much of the information can be obtained from https://msdn.microsoft.com/en-us/library/windows/apps/jj207007(v=vs.105).aspx. First, add this namespace to your code.
  1. using BluetoothConnectionManager;   
  2. using Windows.Networking.Proximity;   

Then initialize the object of the ConnectionManager class.

  1. private ConnectionManager connectionManager;  

We will also add these methods for our initialization as well as for disconnecting the connection along with the method body.

The code is shown below.

  1. protected override void OnNavigatedTo(NavigationEventArgs e)    
  2. {    
  3.     connectionManager.Initialize();    
  4. }    
  5. protected override void OnNavigatedFrom(NavigationEventArgs e)    
  6. {    
  7.     connectionManager.Terminate();    
  8. }  
Now we will move forward to the event handlers. We will be using asynchronous methods for this purpose so just add the async keyword. As specified in my previous articles, that communication is obtained by sending characters. So here also we will be sending characters to the HC05. Let's first add the code for the button's event handler. 
  1. private async void on_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.     string command = "1";    
  4.     await connectionManager.SendCommand(command);    
  5. }    

As seen in the preceding code, we used the async function. We have used a string type variable to store our command. You can use it directly as well. In the preceding code, SendCommand() is a method in the CommentionManager class that is used to send the command. Similarly we will add the events for the other button as well. The code is left for you to do, although the entire project is attached here. As a reference this will be the character for the buttons.

 

  1. On: 1
  2. Off: 0

Now let's code for our connect and disconnect button. The connection will be established only and only if we have a name for the Bluetooth device. The name will be obtained from the TextBox named deviceName. In this TextBox, we will write the device name to be paired. By default it is HC06 for a HC06 device.

Note: This article may not be fully detailed. The main purpose of this article is to understand how this system works and with the hope that you will be able to develop a controlling app for your Arduino. Much of the content for this article has been derived from the article in the Nokia developer forum.

Now as far as the method for the event of the connect button goes, we will use a string variable to get the current text in the TextBox. After we get the text, we will use the AppToDevice method to connect to the device. The code for the AppToDevice method is shown below. We have used the process of Peer discovery. The code will make your concepts clear.

  1. private void connect_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.     //Saving the status    
  4.     s = DeviceName.Text;    
  5.     if (DeviceName.Text == "")    
  6.     {    
  7.         MessageBox.Show("Please enter the device name");    
  8.         connect.Content = "Connect";    
  9.     }    
  10.     else    
  11.     {    
  12.         AppToDevice();    
  13.     }    
  14. }    
  15. private async void AppToDevice()    
  16. {    
  17.     connect.Content = "Connecting...";    
  18.     PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";    
  19.     var pairedDevices = await PeerFinder.FindAllPeersAsync();    
  20.   
  21.     if (pairedDevices.Count == 0)    
  22.     {    
  23.         MessageBox.Show("No paired devices were found.");    
  24.     }    
  25.     else    
  26.     {    
  27.         foreach (var pairedDevice in pairedDevices)    
  28.         {    
  29.             if (pairedDevice.DisplayName == DeviceName.Text)    
  30.             {    
  31.                 connectionManager.Connect(pairedDevice.HostName);    
  32.                 connect.Content = "Connected";      
  33.                 continue;    
  34.             }    
  35.         }    
  36.     }    
  37. }    
Note: In case of any problem, please comment below or reach me by my e mail that is available in my profile.

After we are connected, we can use the on and off button to switch on and off a LED. Let us see an overview of the entire process.

 

  1. After creating the project, add ConnectionManager.cs
  2. Design the UI
  3. Add the capabilities required
  4. Now create the event handlers
  5. Add the code required for initializing the connection
  6. Add code for the on and off button
  7. Add the code for connect button.
  8. Add the code for AppToDevice method

Ever thought why didn't we have a method for disconnect? The reason lies in the fact that when using the method OnNavigatedFrom we terminated the connection. Well, your Windows Phone app is ready. Now you need to test this app. But it won't work unless we apply some engineering skills to the Arduino part. So let's begin with the Arduino part.

Arduino part

Until now we have seen how to develop the Windows Phone app. This section will cover the hardware perspective of your Arduino project and also show the code for the Arduino written in the Arduino processor language. My previous articles did show the communication using a WPF app and a RF communication module. In all of those cases, we used the hardware serial. The Bluetooth communication can also be accomplished using the hardware serial, but what will happen when it is used by another device such as a LCD driver? In that case we need another communication point. For Arduino Mega, we have more than 1 hardware serials but we don't have that facility for Arduino Leonardo. That's the reason to try to this using the software serial of the Arduino.

The SoftwareSerial library has been developed to allow serial communication using the digital pins.

But here again we have some limitations.

 

  1. If using multiple software serial ports, only one can receive data at a time.
  2. Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
  3. Not all pins on the Leonardo and Micro support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

I won't go into the details of MISO, SCK and MOSI pins.

Let's first gather the required components. The list is shown below.

 

  1. Arduino Leonardo
  2. LED
  3. HC05 or HC06
  4. Jumper wires.

Now we will make the circuit. Figure 2 shows the circuit diagram.

Figure 2: Circuit diagram for the connections.

The preceding circuit shows us the connections. I have connected a LED that will turn on when we press the on button on the Windows Phone app. The LED would stop glowing when we press the off button. The connections for the HC06 are to be noted. The HC06 has the following 4 pins:

 

  1. Vcc to be connected to the 3.3V pin of Arduino
  2. Gnd to be connected to the Gnd pin of the Arduino
  3. Rx pin to be connected to pin 11 of the Arduino
  4. Tx pin to be connected to pin 10 of the Arduino
  5. Led to be connected to the pin 13 and Gnd.
The question may develop, what is the difference between HC05 and HC06?

The major difference between the two is that HC05 can send as well as receive signals, that is it can operate both in master as well as in slave mode. The module HC06 doesn't have the facility for the operation in master mode. That is, it can only receive signals. By sending and receiving signals I am specifically referring to the transfer via Bluetooth, not from the device to the Arduino. Figure 2 shows the circuit diagram.

 
Figure 2: Circuit diagram for the Bluetooth system.  

Now after you design this circuit, you need to code for the Arduino. The code is shown below.

  1. #include <SoftwareSerial.h>  
  2. SoftwareSerial BTSerial(10, 11); // RX | TX  
  3. void setup()  
  4. {  
  5.   pinMode(13,OUTPUT); //Led is connected here  
  6.   BTSerial.begin(9600); //Begin the serial communication using bluetooth  
  7. }  
  8. void loop()  
  9. {  
  10.   char c;  
  11.   if(BTSerial.available())  
  12.   {  
  13.     c=BTSerial.read();  
  14.     if(c=='1')  
  15.     {  
  16.       digitalWrite(13,HIGH); //Set pin 13 to high  
  17.     }  
  18.     else if(c=='0')  
  19.     {  
  20.       digitalWrite(13,LOW); //Set pin 13 to low    
  21.     }  
  22.    }  
  23.   }  
  24. }  
 In the preceding code, first we have included the software serial library using:
  1. #include <SoftwareSerial.h>  
After including the library, we need to configure the pins to be used as Rx and Tx. In this case, digital pin 10 is the Rx and digital pin 13 is the Tx. Also we need an object to be used when communicating. This entire process is done with only a single line of code. 
  1. SoftwareSerial BTSerial(10, 11); // RX | TX  
Now the rest of the code is quite clear. It follows the following procedure:
  1. Configure the pins as output or input
  2. In a loop, check whether the serial communication is available or not
  3. If available, read the characters received
  4. Perform corresponding operations with the respective characters
That's it. Everything is done. Now, the following are some problems that may develop.
  1. The Windows Phone app crashes.

    There may develop certain connection problems in which the Windows Phone app may crash. The reason is mainly due to the fact the connection may appear to be establish but it has somehow got disconnected. In that case the best possible course of action is to restart the app. When developing the app, a try catch block may be useful.
     
  2. The LED may not switch off or may not switch on 

    This may develop due to some faulty connections or problems in the Bluetooth module. A proper inspection to the circuit and the module may be useful.
     
  3. Pairing problems

    This is one of the most common problems. Remember the fact that you may need to add the device first into the paired list and then tap it to connect from the settings menu. Then you are required to open your app, enter the name and connect it. When pairing a pin may be asked. By default it is 0000 or 1234. You can change the name and the pin from the AT command menu.  
How to run this system
 
Let's see the procedure involved to run this system:
  1. Switch on the Arduino.
  2. Add the device to your paired list first (important).
  3. Now open the app and write the name of the device and click on the connect button.
  4. You may include a status TextBlock that will display connected when the connection is established. Alternatively you can enable the on and off buttons the instance when connection is established. 
  5. Press the on and off button to see the respective events on the Arduino.  
I had planned to upload a video on YouTube specifically for this article but after trying the insider version for Windows Phone 10, I am facing several bluetooth connectivity issues. The files that are attached to this article, contains the Windows Phone project with a bit of some added features to prevent the app from crashing and the Arduino code. In case of problems with the project, please inform me since I wasn't able to test the project due to the problems encountered on my Windows Phone 10. My guess is that it should work. Congratulatiohs! Your entire Bluetooth controlled Arduino by Windows Phone is ready. Wanna try out more? Try this app already published on the store named Mark 1 Pilot developed by me that I used in controlling a robot. If by any chance this powerup app fails, then you may use the Mark 1 pilot for the purpose.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now