+ All Categories
Home > Documents > Bluetooth Based Automation System

Bluetooth Based Automation System

Date post: 22-Nov-2015
Category:
Upload: umarmiski8751
View: 27 times
Download: 4 times
Share this document with a friend
Description:
bluetooth
Popular Tags:
57
i BLUETOOTH BASED AUTOMATION SYSTEM Armaghan Aized (06-0164) Mazhar Iqbal (06-0424) PROJECT SUPERVISORS: Dr. Waseem Ikram Mr. Shawkat Ali Department of Telecom Engineering National University Of Computer and Emerging Sciences FAST Islamabad
Transcript
  • i

    BLUETOOTH BASED AUTOMATION

    SYSTEM

    Armaghan Aized (06-0164)

    Mazhar Iqbal (06-0424)

    PROJECT SUPERVISORS:

    Dr. Waseem Ikram

    Mr. Shawkat Ali

    Department of Telecom Engineering

    National University Of Computer and Emerging Sciences FAST Islamabad

  • ii

    RESEARCHERS SUBMISSION

    This report is being submitted to the Department of Telecommunication Engineering

    of the National University of Computer and Emerging Sciences in partial fulfillment of the

    requirements for the degree of BE in Telecommunication Engineering.

  • iii

    RESEARCHERS DECLARATION

    It is to declare that the work presented in this report is solely and completely our own.

    This work has not been presented to this institution or any other institution previously.

    Certificate:

    1.Armaghan Aized

    ___________________________

    2.Mazhar Iqbal

    ___________________________

    Date: ____________________

  • iv

    ABSTRACT

    The object of this project is to build a Bluetooth based universal remote system which is able

    to automatically control different features (on/off) of electrical appliances, such as multimedia

    projectors, air conditioners and lights in class rooms and offices. These electrical appliances

    would be controlled by a programmable schedule stored in a computer

  • v

    ACKNOWLEDGEMENTS

    We would first like to thank Allah almighty for providing us with opportunities to

    complete the project on time. We would also like to extend our gratitude to our supervisors

    Dr. Waseem Ikram and Mr. Shawkat Ali, who have always been there to help us throughout

    the project and have always tried to find a solution to our problems

  • vi

    TABLE OF CONTENTSChapter 1.......................................................................................................................................... 1

    Introduction:................................................................................................................................. 1

    Project Phases .............................................................................................................................. 2

    Chapter 2.......................................................................................................................................... 4

    2.1 Universal remote controller ................................................................................................ 4

    2.1.1 How a TV Remote Control Works ................................................................................. 4

    2.1.2 Converting of Remote signal into binary data ................................................................ 6

    2.2 Generated TV Waveforms ..................................................................................................... 7

    2.3 Interfacing with Bluetooth receiver .....................................................................................13

    2.4 Interfacing with IR transmitter.............................................................................................14

    2.5. IR Receiver .........................................................................................................................15

    Chapter 3........................................................................................................................................16

    3.1 Introduction to Bluetooth .....................................................................................................16

    3.2 Bluetooth devices interfacing...............................................................................................16

    3.3 Bluetooth transmitter ...........................................................................................................17

    Chapter 4........................................................................................................................................18

    4.1 Software Development at Server .........................................................................................18

    4.1.1 Graphical User Interface ...............................................................................................18

    CONCLUSION ..............................................................................................................................20

    FUTURE EXTENSION.............................................................................................................22

    BOOKS ......................................................................................................................................23

    REFERENCES ..............................................................................................................................24

    APPENDIX: A ..................................................................................................................................25

    Abbreviations Used....................................................................................................................25

    Annex I ..........................................................................................................................................27

    GUI Code: ..................................................................................................................................27

    Serial Port Communication Code. .............................................................................................35

  • vii

    LIST OF FIGURES

    Fig.1.1 Basic diagram of Bluetooth based automation systemError! Bookmark not defined.

    Fig 1.2 Main Modules of the Bluetooth based Automation SystemError! Bookmark not defined.

    Fig.2.1 SONY Synchronization and data pattern [13] ......... Error! Bookmark not defined.

    Fig2.2a Signal obtained from digital oscilloscope by pressing On/Off buttonError! Bookmark not define

    Fig 2.2b Signal obtained from digital oscilloscope by pressing Temperature Down buttonError!Bookmark

    Fig 2.2c Signal obtained from digital oscilloscope by pressing Temperature Up buttonError!Bookmarkno

    Fig 2.3 USB Bluetooth........................................................... Error! Bookmark not defined.

    Fig 2.4 IR Transmitter [2],[4], [19]........................................ Error! Bookmark not defined.

    Fig 2.5 IR Receiver [2],[4]..................................................................................................... 15

    Fig.4.1 the layout of GUI....................................................................................................... 19

    Fig.4.2 Text File storing the device control frame................................................................. 19

    Table 2.1 SONY Control-S Protocol for TV [13].................. Error! Bookmark not defined.

  • viii

  • CHAPTER1

    1

    Chapter 1 Introduction:

    The main purpose of the project is to build a universal remote control system based

    on Bluetooth that is capable of controlling different devices such as multimedia projector, air

    conditioners and lights in class rooms or offices. The final product will be controlled by a

    remote server, where different devices can be controlled through a predefined schedule. This

    will save power which is wasted when many of these devices remain on even when the

    rooms are not occupied.

    The project requires design and development of both software and hardware. The

    major challenge in the project is to decode the IR signal sent from the remote control of the

    electrical appliances. The purpose is to determine the bit pattern which is used to perform

    various functions. The basic hardware diagram Fig. 1.1 illustrates the working of the system.

    Server (laptop) is used to generate respective codes of the device which is to be controlled. A GUI helps in scheduling and selecting the devices.

    Bluetooth transmitter is used to send the selected device codes

    Bluetooth receiver receives the code and sends it to the microcontroller

  • CHAPTER1

    2

    Fig.1.1 Basic diagram of Bluetooth based automation system

    Project Phases The project is divided into three different modules as shown in Fig. 1.2. The three

    main modules, Universal Remote, Bluetooth Transceiver and Server Modules and their sub

    modules are discussed in detail in the subsequent chapters.

    Bluetooth

    Transmitter

    Bluetooth

    Receiver

    Infrared

    Transmitter

    8051

    Micro-controller

    SignalTransmission Outputto

    Devices

  • CHAPTER1

    3

    Fig 1.2 Main Modules of the Bluetooth based Automation System

    Server

    Bluetooth Based Automation

    System

    Bluetooth Transceiver

    Universal Remote

    controller

    Human

    Interface

    B.T

    Transmitter

    Interface

    B.T

    Receiver

    Interface

    Micro-controller

    Interface

    I.R

    Transmitter

  • CHAPTER3

    Chapter 2 2.1 Universal remote controller

    In order to develop a universal remote controller it is essential to understand the

    working of a remote control. Essentially, all remote controls work in the same manner. When

    a button on a remote control is pressed a unique digital wave form is generated which is

    modulated and transmitted as an Infrared (IR) beam. The IR receiver receives, demodulates

    and decodes the signal to control a specific function of the device/appliance. The unique

    digital wave form is composed of a unique code representing the button selected and a device

    (TV, VCR, Audio, Air conditioner etc.) code. To help understand the waveforms associated

    with different remote functions the SONY TV remote is described. Other remotes work on the

    same principle.

    2.1.1 How a TV Remote Control Works

    The basic principle used in the working of TV remote is the infra red light which is

    being sent between the remote to the TV. There are various bit patterns defined for different

    operation of the television. The code is a seven bit pattern defining the operation. Some of the

    bit patterns are shown in Table 2.1

    When any button is pressed on the remote, the first thing that is sent is the

    synchronization pattern which is a space of 2.4 ms indicating the data is about to be received.

    Fig. 2.1. Synchronization is the main parameter in any transmission medium because without

    properly synchronization, successful transmission never occurs.

    Data bits follow the synchronization pattern. In this case, pulse width modulation is

    used. A 0 is identified as a space of 0.8 ms and a 1 is identified as a space of 1.2ms. Each

    bit is separated by a mark of 0.68 ms. In this way, all the seven data bits are sent. Fig. 2.1.

    Remote Key Digital Code transmitted (decimal binary)

    1 (0) 000 0000

  • CHAPTER3

    2 (1) 000 0001

    3 (2) 000 0010

    4 (3) 000 0011

    5 (4) 000 0100

    6 (5) 000 0101

    7 (6) 000 0110

    8 (7) 000 0111

    9 (8) 000 1000

    0 (9) 000 1001

    Enter (11) 000 1011

    Channel up (16) 001 0000

    Channel down (17) 001 0001

    Volume up (18) 001 0010

    Volume down (19) 001 0011

    Table 2.1 SONY Control-S Protocol for TV [13]

    Fig.2.1 SONY Synchronization and data pattern [13]

    Next comes the device code. For SONY television, the device code is 0 0 0 0. For

    VCR, the device code is 0 0 1 0. This device code is sent using the same method as previously

    used in data bits transmission.

  • CHAPTER3

    The IR has a very low wavelength which does not allow transmission over long

    distances. For this reason modulation is usually done at 38.5 KHz to achieve a desired range

    of at least 15 feet.

    The actual waveform transmitted by a remote was recorded to help us in

    understanding and deciphering the various functions. For this purpose we connected the

    probes of the digital oscilloscope across the IR LED (transmitter) of an Air Conditioner

    remote controller to record the waveform. Fig.2.2. The waveform data was transferred to a

    computer from the digital oscilloscope through the built in USB interface.

    Fig2.2a Signal obtained from digital oscilloscope by pressing On/Off button

    Fig 2.2b Signal obtained from digital oscilloscope by pressing Temperature Down button

    Fig 2.2c Signal obtained from digital oscilloscope by pressing Temperature Up button

    2.1.2 Converting of Remote signal into binary data

    The signal measured at the output of the IR LED had a high frequency noise

    component. The thick line visible in the upper and lower peak of the signal is the high

  • CHAPTER3

    frequency noise. Fig 2.2. Matlab code was developed for two basic reasons, first was to clip off the high noise component, the second was to obtained the signal in binary form which was

    helpful in coding and decoding of that particular signal.

    Matlab Code for converting signal into binary data

    Data= name of CSV file that contains the decoded signal.

    plot(data(:,1),data(:,2)); // plot column1,2

    binary0=(data(:,2)==10.4); // in binary0 store value of column 2 that is =

    10.4

    binary1=(data(:,2)==10.6); // in binary1 store value of column 2 that is =

    10.6

    find(binary==0); // search 0s

    find(binary==1); // search 1s

    data1=ceil(data(i)) // values>.5 consider to 1

    data2=floor(data(i)) // values

  • CHAPTER3

    Code for generating waveform

    #include

    #include

    sbit a=P2^0;

    int j=0;

    void delay(int b) // 0.1 ms delay

    {

    TMOD=0x01;

    while (j

  • CHAPTER3

    void tele14()

    {

    int i;

    int button_0[11]={'0','0','0','0','0','0','0','0','0','0','0'};

    int button_1[11]={'0','0','0','0','0','0','1','0','0','0','0'};

    int button_2[11]={'0','0','0','0','0','1','0','0','0','0','0'};

    int button_3[11]={'0','0','0','0','0','1','1','0','0','0','0'};

    int button_4[11]={'0','0','0','0','1','0','0','0','0','0','0'};

    a=0;

    delay(24); // 2.4 ms synchronization pattern

    a=1;

    delay(6); // 0.6 ms mark separator

    for(i=0;i

  • CHAPTER3

    void tele59()

    {

    int i;

    int button_5[11]={'0','0','0','0','1','0','1','0','0','0','0'};

    int button_6[11]={'0','0','0','0','1','1','0','0','0','0','0'};

    int button_7[11]={'0','0','0','0','1','1','1','0','0','0','0'};

    int button_8[11]={'0','0','0','1','0','0','0','0','0','0','0'};

    int button_9[11]={'0','0','0','1','0','0','1','0','0','0','0'};

    a=0;

    delay(24);

    a=1;

    delay(6);

    for(i=0;i

  • CHAPTER3

    Void main() //button 0

    { a=1;

    delay(6);

    a=0;

    delay(24); // synchronization pattern

    a=1;

    delay(6);

    a=0;

    delay(8); // 7-bit button code

    a=1;

    delay(6);

    a=0;

    delay(8);

    a=1;

    delay(6);

    a=0;

    delay(8);

    a=1;

    delay(6);

    a=0;

  • CHAPTER3

    delay(8);

    a=1;

    delay(6);

    a=0;

    delay(8);

    a=1;

    delay(6);

    a=0;

    delay(8);

    a=1;

    delay(6);

    a=0;

    delay(8);

    a=1;

    delay(6);

    a=0;

    delay(8); // 4-bit device code

    a=1;

    delay(6);

    a=0;

  • CHAPTER3

    delay(8);

    a=1;

    delay(6);

    a=0;

    delay(8);

    a=1;

    delay(6);

    a=0;

    delay(8);

    a=1;

    delay(6);

    }

    2.3 Interfacing with Bluetooth receiver USB dongle is interfaced with microcontroller which allows it to receive device

    operation codes. The microcontroller makes decisions on the basis of received operation code

    and generates respective waveforms. The USB dongle is used as Bluetooth receiver in this

    project the detail of this dongle is given in chapter 3.

    Fig 2.3 USB Bluetooth

  • CHAPTER3

    2.4 Interfacing with IR transmitter The IR transmitting circuit used was based on 555. Fig.2.4. The 555 is used to

    generate the wave of 1 kHz carrier which was the frequency used by AC remote controllers.

    The microcontroller is interfaced with IR transmitter to transmit the waveform to respective

    devices. Micro controllers output was attached to switch S1, as long as this switch in on

    (closed) power is delivered to 555 (Astable Mode) to generate frequency.

    The components R1, R2 and C2 determine the 1 kHz carrier frequency. [19]

    f = 1/ ln(2).C2.(R1+2R2) // .98khz

    high = ln(2).(R1+R2) .C2

    low = ln(2).(R1.C2)

    Fig 2.4 IR Transmitter [2],[4], [19]

  • CHAPTER3

    2.5. IR Receiver To test the working of the IR transmitter circuit an IR Receiver circuit was

    implemented. Fig. 2.5. It is a tunable device that receives the digital data and sends it to a

    filter circuit that we made so that actual data can be extracted, this is actually a device to

    detect the IR signal with frequency up to 1k.

    In the circuit the IR receiver (sensor) is tuned to detect 1 kHz signal [3]. Capacitor C1

    is used as a coupling capacitor. As long as receiver (IR sensor) detects the 1 kHz signal, the

    output signal on pin 1 turns on the 2N2222 transistor which in turns on the LED and the relay.

    Diode D1 is used as a snubber diode to restrict the back emf generated by the relay.

    Fig 2.5 IR Receiver [2],[4]

  • CHAPTER3

    Chapter 3

    3.1 Introduction to Bluetooth The Bluetooth definition is a wireless technology that is a worldwide specification for

    a small form factor, low cost solution that provides link between mobile devices and other

    electronic devices. Similar to 802.11 b/g wireless and many cordless telephone systems,

    Bluetooth operates on 2.4 GHz radio signals.

    The technical specifications of Bluetooth will indicate a maximum transfer rate of

    723 kbps with a range of 65 - 328 feet, all depending on the class of that particular device.

    The technology of Bluetooth wireless is a short range communications method intended to

    replace the cables that connect portable or fixed devices while maintaining the highest levels

    of security. The key features offered by Bluetooth include low power and low cost. The

    specification in Bluetooth defines a uniform structure for a wide range of devices to

    communicate and connect with one another. Unlike other standards of wireless, the Bluetooth

    specification gives product developers both a link layer and application layer definitions,

    which will help support data and voice applications.

    The Bluetooth technology operates in the industrial and scientific band at 2.4 to 2.485

    GHz, using a spread spectrum frequency hopping signals [17], [18] which chops up the data

    being sent and transmits chunks of it on up to 79 bands of 1 MHz width in the range

    2.4Ghz(operating frequency of Bluetooth) where one can achieve a data rate of 1 Mbit/s. The

    Bluetooth standard we used is basically class 2, we used built in Bluetooth in laptops as a

    transmitter and USB dongle is used as Bluetooth receiver.

    3.2 Bluetooth devices interfacing Bluetooth devices works on master slave configuration. A master Bluetooth device

    can communicate with up to seven devices in a Wireless User Group. This network group of

    up to eight devices is called a piconet. The devices can switch roles, by agreement, and the

    slave can become the master at any time. This changing of role and way of connecting the

  • CHAPTER3

    devices is done by adjusting power consumption of different class devices. The frequency and

    baud rates for different classes to communicate are defined. We used class 2 because its baud

    rate is 2400 bps this very baud rate is being used in most remote controller. Bluetooth

    transceiver are installed as it is, the Bluetooth devices we used, need no adjustment. You just

    attach USB dongle to computer and the Laptop Bluetooth itself find that device and also

    sends the data to it and vice versa.

    3.3 Bluetooth transmitter Bluetooth transmitter used to send that codes. Laptop built in Bluetooth is used, that

    is compatible with that of USB dongle. The Bluetooth in the laptops also has same baud rates

    and with same power consumption, thats why we used Laptop built in Bluetooth. Here

    pairing is needed that is helpful in transmitting the data without any query every time,

    different software are available in free for this kind of pairing [13],[14].

  • CHAPTER4

    18

    Chapter 4

    4.1 Software Development at Server At the server we had to develop a user friendly software GUI that can be used to

    select and operate a device. The user selects the ON/OFF button and the devices in the room

    will be turned ON/OFF. Visual C++ has been used to develop the GUI [Annex I]. This

    basically reads the setting set by the user and then write the respective code to the file that is

    to be transferred using Bluetooth. At the receiver end, it waits for the file. On receiving the

    file, data is read from the file and transfers it on the serial port of the computer towards the

    micro-controller. This complete code is available in the CD submitted with the report.

    4.1.1 Graphical User Interface

    We have developed graphical user interface for our software in order to facilitate its

    users. The GUI takes the following three inputs:

    Device name.

    Rooms.

    Operation to be performed.

    After giving the input the user presses OK button. The GUI layout is shown in Fig 4.1. A 1-

    byte frame representing the user selected option is sent to the parallel port. The frame

    represents the address of the location in the microcontroller where the code for the waveform

    is stored. The frame format is

    A7 A6 A5 A4 A3 A2 A1 A0

    0 0 1 0 0 1 0 1

  • CHAPTER4

    19

    Bits A0 and A1 are used to identify the device whether it an Air conditioner or a multimedia projector.

    Bits A2, A3 and A4 are used to identify the room number.

    Bits A5, A6 and A7 are used to identify the operation that is to be performed.

    Fig.4.1 the layout of GUI

    The frame makes the design very generic. One just by changing the values in the frame can

    control many devices and perform many operations. A simple txt file stores the operations

    performed for controlling the devices. Fig 4.2.

  • CHAPTER4

    20

    Fig.4.2 Text File storing the device control frame

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    21

    CONCLUSION

    Pakistan is already facing power crises is now having shortage of almost 10 hours a

    day across Pakistan. In some cities the shortage time is even more than 10 hours. For an under

    developed country like Pakistan it will be helpful and in favor of our country to design and

    implement projects that can save power. We can keep a check on utilization of power with the

    help of systems capable of monitoring specified areas i.e. to see whether power is being used

    by someone or is being wasted. People generally have careless attitude, they forget switching

    of lights, fans and other electrical appliances before leaving there rooms & offices. This can

    now rely on sensors. A sensor is an instrument that responds to a physical stimulus (such as

    heat, light, sound, pressure, magnetism, or motion.)

    A project that leads to the formation of useful product is welcomed by all. Keeping

    the above under consideration we decided to go for a project that would result in a useful

    product especially from power consumption point of view .Our project is aimed to create such

    a project which will be helpful in educational sector, government sector and others .Also this

    product will replace humans and will automatically control the function of many electrical

    devices that include Projectors, Air conditioners and other Electrical appliances. The main

    purpose is to save power & keep a check on power consumption efficiently and effectively.

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    22

    FUTURE EXTENSION

    This project is the just the beginning of using Bluetooth in our daily life applications.

    It can be used for many other purposes as well. One of them is to make the environment

    intelligent. That is, it do take the data from remote source and control the appliances but it

    also has the sensors like temperature sensor, pressure sensor, motion sensors, e.t.c, which also

    control the devices if the room is unoccupied or else the temperature is very hot or cold. It can

    also be used to provide the feedback information back to the user at the central office.

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    23

    BOOKS

    1. 8051 Microcontroller By : Neil McKenzie

    2. Exploring C for microcontrollers . By: Jivan S. Parab

    Vinod G. Shelake

    Rajanish K. Kamat

    Gourish M. Niak

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    24

    REFERENCES

    WEBSITES:

    Internet helped us a lot for this project. We used the search engines to match our

    design with those available on internet. Also we gathered the reference material from the

    internet to complete our report. Some of the sites we used for our help are:

    1. http://digitalradiotech.co.uk/carrier.htm

    2. http://www.tkk.fi/Misc/Electronics/circuits/ir_send.html

    3. http://www.serasidis.gr/circuits/InReCoMe/InReCoMe.htm

    4. http://www.google.com.pk/imgres?imgurl=http://www.circuitstoday.com/wp-

    content/uploads/2008/09/1khz-ir-transmitter-

    circuit.JPG&imgrefurl=http://www.circuitstoday.com/1khz-ir-transmitter-

    circuit&h=403&w=551&sz=34&tbnid=MjUuzAxpenpr6M:&tbnh=97&tbnw=133&prev=

    /images%3Fq%3Dir%2Btransmitter&hl=en&usg=__e7eJ7AqZ6Z32ZrnBXUJDE1T6Am

    k=&sa=X&ei=Bn4_TI_6K8bJca3Hxd4E&ved=0CDEQ9QEwBg

    5. http://www.wikipedia.com

    6. http://imagelab.ee.pusan.ac.kr/young

    7. http://www.dedicated-systems.com

    8. http://jap.hu/electronic/pic.html

    9. http://www.filesaveas.com/index.html

    10. http://www.keil.com/c51/

    11. http://www.freescale.com/webapp/sps/site/homepage.jsp?nodeId=0106B9

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    25

    12. http://www.amphenolrf.com/main.asp?N=0&sid=483B4F007A673CFF&

    13. http://www.rfcode.com/

    14. http://www.ehow.com/how_8446_program-sony-universal.html

    15. http://en.wikipedia.org/wiki/Bluetooth

    16. http://www.brothersoft.com/downloads/bluetooth-usb-dongle-software.html

    17. http://www.picotech.com/data.html?source=Google&keyword=data-logging

    18. http://en.wikipedia.org/wiki/Bluetooth

    19. http://en.wikipedia.org/wiki/555_timer_IC

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    26

    APPENDIX: A

    Abbreviations Used EEROM ................................ Electrically Erasable ROM

    ERAM ................................ Erasable RAM

    FPGA ................................. Field Programmable Gate Array

    FROM ................................ Flash ROM

    GUI . Graphical User Interface

    IF ................................ Intermediate Frequency

    I/O ................................ Input/Output

    IR . Infra-red

    IP . Internet Protocol

    LED ................................. Light Emitting Diode

    MAC ..... Media Access Control

    PNs . PicoNetworks

    PWM .............................. Pulse Width Modulation

    QOS . Quality of service

    RAM ................................ Random Access Memory

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    27

    RF . Radio Frequency

    ROM ................................. Read Only Memory

    RTC ................................ Real Time Clock

    R/X ................................. Receiver

    SPI ................................. Serial Peripheral Interface

    TCP . Transmission Control Protocol

    T/X ................................. Transmitter

    UART ................................ Universal Asynchronous Receiver Transmitter

    USB ................................ Universal Storage Bus

    VOIP .. Voice over IP

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    28

    Annex I GUI Code: #pragma once

    namespace Device

    { using namespace System;

    using namespace System::ComponentModel;

    using namespace System::Collections;

    using namespace System::Windows::Forms;

    using namespace System::Data;

    using namespace System::Drawing;

    using namespace System::IO;

    /* WARNING: If you change the name of this class, you will need to change

    the Resource File Name' property for the managed resource compiler tool associated

    with all .resx files this class depends on. Otherwise, the designers will not be able to interact

    properly with localized resources associated with this form.*/

    public ref class Form1 : public System::Windows::Forms::Form

    { public:

    Form1(void)

    { InitializeComponent(); }

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    29

    protected:

    Form1()

    { if (components)

    { delete components; }

    }

    private: System::Windows::Forms::ComboBox^ Devices;

    protected:

    protected:

    private: System::Windows::Forms::ComboBox^ comboBox2;

    private: System::Windows::Forms::ComboBox^ comboBox3;

    private: System::Windows::Forms::Label^ label1;

    private: System::Windows::Forms::Label^ label2;

    private: System::Windows::Forms::Label^ label3;

    private: System::Windows::Forms::Button^ button1;

    private: System::Windows::Forms::Button^ button2;

    private: System::Windows::Forms::Label^ label4;

    private:

    System::ComponentModel::Container ^components;

    pragma region Windows Form Designer generated code

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    30

    /* Required method for Designer support - do not modify the contents of this method

    with the code editor.*/

    void InitializeComponent(void)

    { this->Devices = (gcnew System::Windows::Forms::ComboBox());

    this->comboBox2 = (gcnew System::Windows::Forms::ComboBox());

    this->comboBox3 = (gcnew System::Windows::Forms::ComboBox());

    this->label1 = (gcnew System::Windows::Forms::Label());

    this->label2 = (gcnew System::Windows::Forms::Label());

    this->label3 = (gcnew System::Windows::Forms::Label());

    this->button1 = (gcnew System::Windows::Forms::Button());

    this->button2 = (gcnew System::Windows::Forms::Button());

    this->label4 = (gcnew System::Windows::Forms::Label());

    this->SuspendLayout();

    // Devices

    this->Devices->AccessibleName = L"Devices";

    this->Devices->DropDownStyle =

    System::Windows::Forms::ComboBoxStyle::DropDownList;

    this->Devices->FormattingEnabled = true;

    this->Devices->Items->AddRange(gcnew cli::array< System::Object^ >(3)

    {L"Television", L"Air Conditioner", L"Tube Light"});

    this->Devices->Location = System::Drawing::Point(49, 89);

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    31

    this->Devices->Name = L"Devices";

    this->Devices->Size = System::Drawing::Size(111, 21);

    this->Devices->TabIndex = 0;

    this->Devices->Tag = L"Devices";

    this->Devices->SelectedIndexChanged += gcnew

    System::EventHandler(this, &Form1::comboBox3_SelectedIndexChanged);

    this->Devices->MouseEnter += gcnew System::EventHandler(this,

    &Form1::comboBox3_SelectedIndexChanged);

    this->comboBox2->DropDownStyle=

    System::Windows::Forms::ComboBoxStyle::DropDownList;

    this->comboBox2->FormattingEnabled = true;

    this->comboBox2->Items->AddRange(gcnew cli::array< System::Object^

    >(3) {L"Room No. 1", L"Room No. 2", L"Room No. 3"});

    this->comboBox2->Location = System::Drawing::Point(237, 90);

    this->comboBox2->Name = L"comboBox2";

    this->comboBox2->Size = System::Drawing::Size(124, 21);

    this->comboBox2->TabIndex = 1;

    this->comboBox3->AccessibleRole =

    System::Windows::Forms::AccessibleRole::None;

    this->comboBox3->DropDownStyle=

    System::Windows::Forms::ComboBoxStyle::DropDownList;

    this->comboBox3->FormattingEnabled = true;

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    32

    this->comboBox3->Items->AddRange(gcnew cli::array< System::Object^

    >(2) {L"On", L"Off"});

    this->comboBox3->Location = System::Drawing::Point(411, 89);

    this->comboBox3->Name = L"comboBox3";

    this->comboBox3->Size = System::Drawing::Size(128, 21);

    this->comboBox3->TabIndex = 2;

    this->comboBox3->SelectedIndexChanged += gcnew

    System::EventHandler(this, &Form1::comboBox3_SelectedIndexChanged);

    this->label1->AutoSize = true;

    this->label1->Location = System::Drawing::Point(52, 46);

    this->label1->Name = L"label1";

    this->label1->Size = System::Drawing::Size(46, 13);

    this->label1->TabIndex = 3;

    this->label1->Text = L"Devices";

    this->label1->Click += gcnew System::EventHandler(this,

    &Form1::label1_Click);

    this->label2->AutoSize = true;

    this->label2->Location = System::Drawing::Point(240, 51);

    this->label2->Name = L"label2";

    this->label2->Size = System::Drawing::Size(40, 13);

    this->label2->TabIndex = 4;

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    33

    this->label2->Text = L"Rooms";

    this->label3->AutoSize = true;

    this->label3->Location = System::Drawing::Point(406, 51);

    this->label3->Name = L"label3";

    this->label3->Size = System::Drawing::Size(53, 13);

    this->label3->TabIndex = 5;

    this->label3->Text = L"Operation";

    this->button1->Location = System::Drawing::Point(162, 163);

    this->button1->Name = L"button1";

    this->button1->Size = System::Drawing::Size(117, 38);

    this->button1->TabIndex = 6;

    this->button1->Text = L"Ok";

    this->button1->UseVisualStyleBackColor = true;

    this->button1->Click += gcnew System::EventHandler(this,

    &Form1::button1_Click);

    this->button2->Location = System::Drawing::Point(342, 163);

    this->button2->Name = L"button2";

    this->button2->Size = System::Drawing::Size(117, 38);

    this->button2->TabIndex = 7;

    this->button2->Text = L"Cancel";

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    34

    this->button2->UseVisualStyleBackColor = true;

    this->button2->Click += gcnew System::EventHandler(this,

    &Form1::button2_Click);

    this->label4->AutoSize = true;

    this->label4->Location = System::Drawing::Point(205, 253);

    this->label4->Name = L"label4";

    this->label4->Size = System::Drawing::Size(0, 13);

    this->label4->TabIndex = 8;

    this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

    this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

    this->ClientSize = System::Drawing::Size(647, 338);

    this->Controls->Add(this->label4);

    this->Controls->Add(this->button2);

    this->Controls->Add(this->button1);

    this->Controls->Add(this->label3);

    this->Controls->Add(this->label2);

    this->Controls->Add(this->label1);

    this->Controls->Add(this->comboBox3);

    this->Controls->Add(this->comboBox2);

    this->Controls->Add(this->Devices);

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    35

    this->FormBorderStyle =

    System::Windows::Forms::FormBorderStyle::SizableToolWindow;

    this->Name = L"Form1";

    this->Text = L"Form1";

    this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

    this->ResumeLayout(false);

    this->PerformLayout();

    }

    #pragma endregion

    private: System::Void comboBox3_SelectedIndexChanged(System::Object^ sender,

    System::EventArgs^ e) {}

    private: System::Void label1_Click(System::Object^ sender, System::EventArgs^ e)

    { }

    private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)

    {}

    private: System::Void textBox1_TextChanged(System::Object^ sender,

    System::EventArgs^ e) {}

    private: System::Void button1_Click(System::Object^ sender, System::EventArgs^

    e)

    { String^ fileName = "armaghan.txt";

    String^ comb3="";

    if(comboBox3->SelectedItem->ToString()=="On")

    comb3="1";

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    36

    else if (comboBox3->SelectedItem->ToString()=="Off")

    comb3="0";

    StreamWriter^ sw = gcnew StreamWriter(fileName,true);

    sw->Write(Devices->SelectedItem->ToString()

    +"\t"+comboBox2->SelectedItem->ToString()

    +"\t"+comb3+"\n");

    sw->WriteLine();

    sw->Close();

    label4->Text="armaghan.txt written";

    }

    private: System::Void button2_Click(System::Object^ sender,

    System::EventArgs^ e) {}

    };

    }

    Serial Port Communication Code. #region Namespace Inclusions

    using System;

    using System.Data;

    using System.Text;

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    37

    using System.Drawing;

    using System.IO.Ports;

    using System.Windows.Forms;

    using System.ComponentModel;

    using System.Collections.Generic;

    using SerialPortTerminal.Properties;

    #endregion

    namespace SerialPortTerminal

    {

    #region Public Enumerations

    public enum DataMode { Text, Hex }

    public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };

    #endregion

    public partial class frmTerminal : Form

    {

    #region Local Variables

    // The main control for communicating through the RS-232 port

    private SerialPort comport = new SerialPort();

    // Various colors for logging info

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    38

    private Color[] LogMsgTypeColor = { Color.Blue, Color.Green,

    Color.Black, Color.Orange, Color.Red };

    // Temp holder for whether a key was pressed

    private bool KeyHandled = false;

    #endregion

    #region Constructor

    public frmTerminal()

    {

    InitializeComponent();

    // Restore the users settings

    InitializeControlValues();

    // Enable/disable controls based on the current state

    EnableControls();

    // When data is recieved through the port, call this method

    comport.DataReceived += new

    SerialDataReceivedEventHandler(port_DataReceived);

    }

    #endregion

    #region Local Methods

    // Save the user's settings

    private void SaveSettings()

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    39

    {

    Settings.Default.BaudRate = int.Parse(cmbBaudRate.Text);

    Settings.Default.DataBits = int.Parse(cmbDataBits.Text);

    Settings.Default.DataMode = CurrentDataMode;

    Settings.Default.Parity = (Parity)Enum.Parse(typeof(Parity),

    cmbParity.Text);

    Settings.Default.StopBits = (StopBits)Enum.Parse(typeof(StopBits),

    cmbStopBits.Text);

    Settings.Default.PortName = cmbPortName.Text;

    Settings.Default.Save();

    }

    // Populate the form's controls with default settings.

    private void InitializeControlValues()

    {

    cmbParity.Items.Clear();

    cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));

    cmbStopBits.Items.Clear();

    cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));

    cmbParity.Text = Settings.Default.Parity.ToString();

    cmbStopBits.Text = Settings.Default.StopBits.ToString();

    cmbDataBits.Text = Settings.Default.DataBits.ToString();

    cmbParity.Text = Settings.Default.Parity.ToString();

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    40

    cmbBaudRate.Text = Settings.Default.BaudRate.ToString();

    CurrentDataMode = Settings.Default.DataMode;

    cmbPortName.Items.Clear();

    foreach (string s in SerialPort.GetPortNames())

    cmbPortName.Items.Add(s);

    if (cmbPortName.Items.Contains(Settings.Default.PortName))

    cmbPortName.Text = Settings.Default.PortName;

    else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex

    = 0;

    else

    {

    MessageBox.Show(this, "There are no COM Ports detected

    on this computer.\nPlease install a COM Port and restart this

    app.", "No COM Ports Installed", MessageBoxButtons.OK,

    MessageBoxIcon.Error);

    this.Close();

    }

    }

    /// Enable/disable controls based on the app's current state.

    private void EnableControls()

    { // Enable/disable controls based on whether the port is open or not

    gbPortSettings.Enabled = !comport.IsOpen;

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    41

    txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;

    if (comport.IsOpen) btnOpenPort.Text = "&Close Port";

    else btnOpenPort.Text = "&Open Port";

    }

    // Send the user's data currently entered in the 'send' box

    private void SendData()

    {

    if (CurrentDataMode == DataMode.Text)

    { // Send the user's text straight out the port

    comport.Write(txtSendData.Text);

    // Show in the terminal window the user's text

    Log(LogMsgType.Outgoing, txtSendData.Text + "\n");

    }

    else

    { try

    {

    // Convert the user's string of hex digits (ex: B4 CA

    E2) to a byte //array

    byte[] data =

    HexStringToByteArray(txtSendData.Text);

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    42

    // Send the binary data out the port

    comport.Write(data, 0, data.Length);

    // Show the hex digits on in the terminal window

    Log(LogMsgType.Outgoing,ByteArrayToHexString(data)+"\n");

    }

    catch (FormatException)

    {

    // Inform the user if the hex string was not properly formatted

    Log(LogMsgType.Error, "Not properly formatted hex string:

    " + txtSendData.Text + "\n");

    }

    }

    txtSendData.SelectAll();

    }

    // Log data to the terminal window

    private void Log(LogMsgType msgtype, string msg)

    {

    rtfTerminal.Invoke(new EventHandler(delegate

    { rtfTerminal.SelectedText = string.Empty;

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    43

    rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont,

    FontStyle.Bold);

    rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];

    rtfTerminal.AppendText(msg);

    rtfTerminal.ScrollToCaret();

    }));

    }

    // Convert a string of hex digits (ex: E4 CA B2) to a byte array

    // Returns an array of bytes.

    private byte[] HexStringToByteArray(string s)

    {

    s = s.Replace(" ", "");

    byte[] buffer = new byte[s.Length / 2];

    for (int i = 0; i < s.Length; i += 2)

    buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);

    return buffer;

    }

    //Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)

    //Returns a well formatted string of hex digits with spacing

    private string ByteArrayToHexString(byte[] data)

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    44

    {

    StringBuilder sb = new StringBuilder(data.Length * 3);

    foreach (byte b in data)

    sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));

    return sb.ToString().ToUpper();

    }

    #endregion

    #region Local Properties

    private DataMode CurrentDataMode

    {

    get

    { if (rbHex.Checked) return DataMode.Hex;

    else return DataMode.Text;

    }

    set

    {

    if (value == DataMode.Text) rbText.Checked = true;

    else rbHex.Checked = true;

    }

    }

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    45

    #endregion

    #region Event Handlers

    private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs

    e)

    { // Show the user the about dialog

    (new frmAbout()).ShowDialog(this);

    }

    private void frmTerminal_Shown(object sender, EventArgs e)

    {

    Log(LogMsgType.Normal, String.Format("Application Started at {0}\n",

    DateTime.Now));

    }

    private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)

    { // The form is closing, save the user's preferences

    SaveSettings();

    }

    private void rbText_CheckedChanged(object sender, EventArgs e)

    { if (rbText.Checked) CurrentDataMode = DataMode.Text;

    }

    private void rbHex_CheckedChanged(object sender, EventArgs e)

    { if (rbHex.Checked) CurrentDataMode = DataMode.Hex;

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    46

    }

    private void cmbBaudRate_Validating(object sender, CancelEventArgs e)

    { int x; e.Cancel = !int.TryParse(cmbBaudRate.Text, out x);

    }

    private void cmbDataBits_Validating(object sender, CancelEventArgs e)

    { int x; e.Cancel = !int.TryParse(cmbDataBits.Text, out x);

    }

    private void btnOpenPort_Click(object sender, EventArgs e)

    { // If the port is open, close it.

    if (comport.IsOpen) comport.Close();

    else

    { // Set the port's settings

    comport.BaudRate = int.Parse(cmbBaudRate.Text);

    comport.DataBits = int.Parse(cmbDataBits.Text);

    comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits),

    cmbStopBits.Text);

    comport.Parity = (Parity)Enum.Parse(typeof(Parity),

    cmbParity.Text);

    comport.PortName = cmbPortName.Text;

    // Open the port

    comport.Open();

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    47

    }

    // Change the state of the form's controls

    EnableControls();

    // If the port is open, send focus to the send data box

    if (comport.IsOpen) txtSendData.Focus();

    }

    private void btnSend_Click(object sender, EventArgs e)

    { SendData(); }

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)

    { // This method will be called when there is data waiting in the port's buffer

    // Determain which mode (string or binary) the user is in

    if (CurrentDataMode == DataMode.Text)

    { // Read all the data waiting in the buffer

    string data = comport.ReadExisting();

    // Display the text to the user in the terminal

    Log(LogMsgType.Incoming, data);

    }

    else

    { // Obtain the number of bytes waiting in the port's buffer

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    48

    int bytes = comport.BytesToRead;

    // Create a byte array buffer to hold the incoming data

    byte[] buffer = new byte[bytes];

    // Read the data from the port and store it in our buffer

    comport.Read(buffer, 0, bytes);

    // Show the user the incoming data in hex format

    Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));

    }

    }

    private void txtSendData_KeyDown(object sender, KeyEventArgs e)

    { // If the user presses [ENTER], send the data now

    if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true;

    SendData(); }

    }

    private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)

    { e.Handled = KeyHandled;

    }

    #endregion

    }

    }

  • BLUETOOTHBASEDAUTOMATIONSYSTEM

    49


Recommended