.NET Gadgeteer Bluetooth to Control Relay Circuits

Here is a simple adaptation of Marco Minerva’s previous example: Controlling a Gadgeteer device using Bluetooth Module and 32feet.NET library.  This application uses the GHI Electronics Bluetooth Module to control the relays on a Seeed Relay Module.  You can use this scenario to turn on lights, start a motor, or start or stop any electrical circuit within the Wattage limits of the relays, anywhere within range of a .NET Gadgeteer device with the Bluetooth and relay modules.

.NET Gadgeteer Device with Bluetooth and Relays

When setting up the device in the Visual Studio Designer, do not include the Bluetooth module, because we are using Eduardo Velloso’s driver for the GHI Electronics Bluetooth Module.  Download the driver from CodePlex and add the Bluetooth.cs file to your project. Connect the module to socket 9.

The code is simple, just the initialization of the Bluetooth module and an event handler to process messages coming to the device from the application running the 32Feet library on your computer. I used a button to test the relays before starting them from the Bluetooth control; you want to be sure you have it right when a circuit is connected to 120 volts.  I used relays 1 and 3, leaving two more to connect to other circuits.

using Microsoft.SPOT;
using Gadgeteer.Modules.GHIElectronics;
using Gadgeteer.Modules.Velloso;

namespace GadgeteerBluetoothRelays
{
    public partial class Program
    {
        Bluetooth bluetooth;
        Bluetooth.Client client;

        void ProgramStarted()
        {
            bluetooth = new Bluetooth(9);
            client = bluetooth.ClientMode;

            bluetooth.SetDeviceName("GadgeteerBluetooth");
            bluetooth.SetPinCode("1234");
            bluetooth.DataReceived +=
                new Bluetooth.DataReceivedHandler(bluetooth_DataReceived);
            client.EnterPairingMode();

            button.ButtonPressed +=
                new Button.ButtonEventHandler(button_ButtonPressed);
            Debug.Print("Program Started");
        }

        void bluetooth_DataReceived(Bluetooth sender, string data)
        {
            if (data.IndexOf("Start 1") != -1)
                relays.Relay1 = true;
            if(data.IndexOf("Stop 1") != -1)
                relays.Relay1 = false;
            if (data.IndexOf("Start 3") != -1)
                relays.Relay3 = true;
            if (data.IndexOf("Stop 3") != -1)
                relays.Relay3 = false;
        }

        void button_ButtonPressed(Button sender, Button.ButtonState state)
        {
            if (!button.IsLedOn)
            {
                relays.Relay1 = true;
                button.TurnLEDOn();
            }
            else
            {
                relays.Relay1 = false;
                button.TurnLEDOff();
            }
        }
    }
}

The Bluetooth Control Application using 32 Feet Library

The control application is Marco’s application with a couple of names changed.  The code under the previous heading uses the name GadgeteerBluetooth to initialize the module: bluetooth.SetDeviceName(“GadgeteerBluetooth”), so to connect to the Bluetooth device from the client, you have to change a couple of things, then the following UI will work as expected.

Send Message to Bluetooth Relays

Send Message to Bluetooth Relays

The client code I used is shown in the following MainWindow.xaml.cs file. The complete application is available at download.  Use the BluetoothControl solution, and adapt it to the names used in this example.

using System;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;

using System.Diagnostics;

using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;

using System.ComponentModel;
using System.IO;

namespace BluetoothControlRelays
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private BluetoothClient bluetooth;
        private Stream bluetoothStream;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!BluetoothRadio.IsSupported)
            {
                lblStatus.Text = "Bluetooth not supported";
                btnSearchDevice.IsEnabled = false;
            }
            else if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
            {
                lblStatus.Text = "Bluetooth is off";
                btnSearchDevice.IsEnabled = false;
            }
        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(e.Uri.ToString());
        }

        private void btnSearchDevice_Click(object sender, RoutedEventArgs e)
        {
            lblStatus.Text = "Searching for devices...";
            btnSearchDevice.IsEnabled = false;
            BackgroundWorker bwDiscoverDevices = new BackgroundWorker();
            bwDiscoverDevices.DoWork += new DoWorkEventHandler(bwDiscoverDevices_DoWork);
            bwDiscoverDevices.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwDiscoverDevices_RunWorkerCompleted);
            bwDiscoverDevices.RunWorkerAsync();
        }

        private void bwDiscoverDevices_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                bluetooth = new BluetoothClient();
                var gadgeteerDevice = bluetooth.DiscoverDevices().Where(d => d.DeviceName == "GadgeteerBluetooth").FirstOrDefault();
                if (gadgeteerDevice != null)
                {
                    bluetooth.SetPin("1234");
                    bluetooth.Connect(gadgeteerDevice.DeviceAddress, BluetoothService.SerialPort);
                    bluetoothStream = bluetooth.GetStream();
                    e.Result = true;
                }
                else
                {
                    e.Result = false;
                }
            }
            catch (Exception)
            {
                e.Result = false;
            }
        }

        private void bwDiscoverDevices_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnSearchDevice.IsEnabled = true;
            var deviceFound = (bool)e.Result;
            if (!deviceFound)
            {
                lblStatus.Text = "No device found";
            }
            else
            {
                lblStatus.Text = "Connected to GadgeteerBluetooth";
                btnSendMessage.IsEnabled = true;
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (bluetoothStream != null)
            {
                bluetoothStream.Close();
                bluetoothStream.Dispose();
            }
        }

        private void btnSendMessage_Click(object sender, RoutedEventArgs e)
        {
            if (bluetooth.Connected && bluetoothStream != null)
            {
                var buffer = System.Text.Encoding.UTF8.GetBytes(txtMessage.Text);
                bluetoothStream.Write(buffer, 0, buffer.Length);
                txtMessage.Text = string.Empty;
            }
        }
    }
}
About these ads

, ,

  1. .NET Gadgeteer Bluetooth to Control Relay Circuits « Integral Design » AppBase

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: