This document provides a final project report for a conceptual design of a mobile climate control application for Android. The project aims to demonstrate a product that would enable control and automation of comfort settings within a recreational vehicle through a temperature sensor, microcontroller, relays, and Bluetooth communication. The report details the hardware and software design of the system, including the use of an Arduino microcontroller, Bluetooth and relay shields, an Android app interface, and unit testing of the integrated system. It evaluates the project objectives, timeline, costs, risks, and lessons learned to conceptualize a system that monitors and wirelessly controls a vehicle's interior temperature via a smartphone.
DESIGN OF TEMPERATURE BASED FAN SPEED CONTROL and MONITORING USING ARDUINORatnesh Kumar chaurasia
This practical temperature controller controls the temperature of any device according to its requirement for any industrial application, it also has a feature of remote speed control.
Arduino based automatic temperature controlled fan speed regulatorEdgefxkits & Solutions
Using an analog temperature LM35 interfaced to the built in ADC of a programmed Arduino to develop varying duty cycle of PWM output for a driver IC to run a DC motor automatically according to the sensed temperature at different speed based on the temperature sensed.
This project proposes automatic detection of human and energy saving room architecture to reduce standby power consumption and to make the temperature of the room easily controllable with an IR sensor and Lm35 temperature sensor using air conditioner . The proposed auto-detection of human done using the IR sensor to indicate the entering or exit ofthe persons. Microcontroller continuously monitors the infrared receiver. When any object pass throughthe IR receiver then the IR rays falling on the receiver are obstructed, this obstruction is sensed by the microcontroller ATMEGA16.When the temperature of the room is varied then the lm35 temperature sensor converts this temperature change into voltage which is then sensed by the microcontroller ATMEGA16 .
In such cases our project is aimed at starting one ac among both depending upon the temperature value at a particular room .If the temperature on the particular room is above certain range then the AC in that room will start up and during this time the AC in the other room will remain switched off. When the temperature goes below 25 degree in the room where AC is already on will be switched off automatically. Then if the temperature on the other room during the time is above 30degree then the AC in that room will start up and vice versa .The second feature of our project is aimed at switching of the AC automatically when there is absence of human beings in a particular room .The entire scheme is designed using number of ATMEGA16 microcontrollers , temperature sensors , digital counter ,IR sensors , relay etc.
This project will solve the day-to-day problem where AC’s do not start up due to low voltage generally in rural areas .This will start the AC depending upon the temperature label in a room by sharing the load .Also this project can be extended for controlling the temperature in more rooms in an apartment.
DESIGN OF TEMPERATURE BASED FAN SPEED CONTROL and MONITORING USING ARDUINORatnesh Kumar chaurasia
This practical temperature controller controls the temperature of any device according to its requirement for any industrial application, it also has a feature of remote speed control.
Arduino based automatic temperature controlled fan speed regulatorEdgefxkits & Solutions
Using an analog temperature LM35 interfaced to the built in ADC of a programmed Arduino to develop varying duty cycle of PWM output for a driver IC to run a DC motor automatically according to the sensed temperature at different speed based on the temperature sensed.
This project proposes automatic detection of human and energy saving room architecture to reduce standby power consumption and to make the temperature of the room easily controllable with an IR sensor and Lm35 temperature sensor using air conditioner . The proposed auto-detection of human done using the IR sensor to indicate the entering or exit ofthe persons. Microcontroller continuously monitors the infrared receiver. When any object pass throughthe IR receiver then the IR rays falling on the receiver are obstructed, this obstruction is sensed by the microcontroller ATMEGA16.When the temperature of the room is varied then the lm35 temperature sensor converts this temperature change into voltage which is then sensed by the microcontroller ATMEGA16 .
In such cases our project is aimed at starting one ac among both depending upon the temperature value at a particular room .If the temperature on the particular room is above certain range then the AC in that room will start up and during this time the AC in the other room will remain switched off. When the temperature goes below 25 degree in the room where AC is already on will be switched off automatically. Then if the temperature on the other room during the time is above 30degree then the AC in that room will start up and vice versa .The second feature of our project is aimed at switching of the AC automatically when there is absence of human beings in a particular room .The entire scheme is designed using number of ATMEGA16 microcontrollers , temperature sensors , digital counter ,IR sensors , relay etc.
This project will solve the day-to-day problem where AC’s do not start up due to low voltage generally in rural areas .This will start the AC depending upon the temperature label in a room by sharing the load .Also this project can be extended for controlling the temperature in more rooms in an apartment.
Automatic irrigation system using ArduinoBalajiK109
In this project time operated electrical appliances like lamp and AC motor is locally customized device capable of switching electrical devices with respect to time and can be used for both home and commercial purposes. In this project we will be able to control the on and off of your devices between the time you want. They may be a light or motor etc., we will use the arduino Mega 2560, and the RTC 1307 to show and control the time. You can set the "ON" hour and the "OFF" hour.
Arduino based intelligent greenhouse ProjectAmit Saini
Final Year Project : - Arduino based ‘Intelligent Green House'
A complete greenhouse monitoring and controlling system ,that is automated, updating each and every detail on internet that can be accessed from anywhere. For sensors, it uses a light sensor, temperature sensor, moisture sensor, humidity sensor and all the updates will be available on internet through Ethernet shield through which the user can take care of the garden even when not at home.
Temperature based fan speed control & monitoring usingJagannath Dutta
Our object of making this project is for reducing the power consumption. And also to assist people who are disabled and are unable to control the speed of fan.
Industrial Process Management Using LabVIEWIOSR Journals
Nowadays process management is a tedious task in the industry. We plan to propose a LabVIEW
based intelligent multi parameter monitoring system designed using RS232 and Microcontroller aids in the
measurement and control of various Global Parameters. For data collection in the industry is a difficult task in
real time execution of events with industrial process control and automation. We proposed two slaves for
measuring various industrial parameters to monitor and control industrial process. Data acquired from each
slave is processed and sent to Master that compile data received from different slaves and send this information
to the system configured with LabVIEW platform. This enables us to view and track the online changes
encountered in the particular parameter of all the parameters. One of the main advantages of this proposal is, it
allows us to view all the parameter readings simultaneously on the front panel in LabVIEW. The Graph drawn
on the front panel keeps on tracking the changes on the parameter. The parameters supported by this project
includes: current, voltage, temperature, frequency, light intensity, logic switches, water level identifier, and
alarm. This Project can be implemented in any of the process industries where there is a need for Simultaneous
and fast acquiring of data and control
Major Project Report on overheat and smoke detection with GSM module in final year of Undergraduate course in Electronics and Communication Engineering
This paper presents an innovative prototype design of electric fan with smart characteristics. This electric fan uses a microcontroller to produce an automation function. It also has a unique double feature designs, such as using 2 fans, 2 Light Emitting Diodes (LED) and 2 sensors. This is to ensure the cooling process operates more efficiently and effectively, especially for a large space application and in hot weather due to global warming. By applying the circuit, it offers a better life for human. It is really practical for senior citizens to make their life simpler. The circuit is also suitable for disabled people who have difficulty to switch on the fan manually. Lastly, the circuit can be manipulated by diversifying its function as a detector, where it can produce an alarm signal when emergency case occurs such as the house or premise is on fire.
Robot which can be controlled remotely by an Android smartphone.
The robot works through a “AC Robot” android app. The app is designed by us and made available to open source. The app and source code can be downloaded from the url (http://tinyurl.com/kh7zgex).
Automatic irrigation system using ArduinoBalajiK109
In this project time operated electrical appliances like lamp and AC motor is locally customized device capable of switching electrical devices with respect to time and can be used for both home and commercial purposes. In this project we will be able to control the on and off of your devices between the time you want. They may be a light or motor etc., we will use the arduino Mega 2560, and the RTC 1307 to show and control the time. You can set the "ON" hour and the "OFF" hour.
Arduino based intelligent greenhouse ProjectAmit Saini
Final Year Project : - Arduino based ‘Intelligent Green House'
A complete greenhouse monitoring and controlling system ,that is automated, updating each and every detail on internet that can be accessed from anywhere. For sensors, it uses a light sensor, temperature sensor, moisture sensor, humidity sensor and all the updates will be available on internet through Ethernet shield through which the user can take care of the garden even when not at home.
Temperature based fan speed control & monitoring usingJagannath Dutta
Our object of making this project is for reducing the power consumption. And also to assist people who are disabled and are unable to control the speed of fan.
Industrial Process Management Using LabVIEWIOSR Journals
Nowadays process management is a tedious task in the industry. We plan to propose a LabVIEW
based intelligent multi parameter monitoring system designed using RS232 and Microcontroller aids in the
measurement and control of various Global Parameters. For data collection in the industry is a difficult task in
real time execution of events with industrial process control and automation. We proposed two slaves for
measuring various industrial parameters to monitor and control industrial process. Data acquired from each
slave is processed and sent to Master that compile data received from different slaves and send this information
to the system configured with LabVIEW platform. This enables us to view and track the online changes
encountered in the particular parameter of all the parameters. One of the main advantages of this proposal is, it
allows us to view all the parameter readings simultaneously on the front panel in LabVIEW. The Graph drawn
on the front panel keeps on tracking the changes on the parameter. The parameters supported by this project
includes: current, voltage, temperature, frequency, light intensity, logic switches, water level identifier, and
alarm. This Project can be implemented in any of the process industries where there is a need for Simultaneous
and fast acquiring of data and control
Major Project Report on overheat and smoke detection with GSM module in final year of Undergraduate course in Electronics and Communication Engineering
This paper presents an innovative prototype design of electric fan with smart characteristics. This electric fan uses a microcontroller to produce an automation function. It also has a unique double feature designs, such as using 2 fans, 2 Light Emitting Diodes (LED) and 2 sensors. This is to ensure the cooling process operates more efficiently and effectively, especially for a large space application and in hot weather due to global warming. By applying the circuit, it offers a better life for human. It is really practical for senior citizens to make their life simpler. The circuit is also suitable for disabled people who have difficulty to switch on the fan manually. Lastly, the circuit can be manipulated by diversifying its function as a detector, where it can produce an alarm signal when emergency case occurs such as the house or premise is on fire.
Robot which can be controlled remotely by an Android smartphone.
The robot works through a “AC Robot” android app. The app is designed by us and made available to open source. The app and source code can be downloaded from the url (http://tinyurl.com/kh7zgex).
you can be friend with me on orkut
"mangalforyou@gmail.com" : i belive in sharing the knowledge so please send project reports ,seminar and ppt. to me .
Location Tracking of Android Device Based on SMS.iCreateWorld
If an android user wants to know the location of Android device then user has to send SMS to designated device. So that he can locate device either by making it ring or gets actual location of device using GPS or network provider.
Low Power Context Aware Hierarchical System DesignHoopeer Hoopeer
Embedded systems have come to play central roles in our lives. Smart, wearable ultra low power systems have become prevalent thanks to advances in sensing, communication,
computation, and miniaturization. Though the individual subsystems have improved, designing these systems is a challenge since their compute, communication, and sensing components are tightly coupled. System engineers creating these devices must consider the whole hardware/software stack and the application at hand in order to stay within the limited energy budget of these systems. There has been a lot of research focused on each particular facet of low power systems, yet few have tried to approach the problem from the system and application integration level. The objective of the proposed research is to explore various hierarchical architectures through the development and deployment of systems for Geo-spatial and medical applications.
A smart switch to connect and disconnect electrical devices at home by using ...Mounika G
“A Smart Switch to Connect and Disconnect Electrical Devices at Home by Using Open Source Platform” has been developed by integrating features of all the hardware components and software used. Presence of every module has been reasoned out and placed carefully thus contributing to the best working of the unit. Secondly, using highly advanced Raspberry pi board and with the help of growing technology
The. Smart Switch is connected to internet via Wi-Fi TM, through a computer, smart phone, ... Switch server, which will open a configuration page to write the data of the user's ..... Source.
Smartphone fpga based balloon payload using cots componentseSAT Journals
Abstract
This paper describes a low cost architecture of multi sensor remote sensing balloon payload design for prototyping student’s micro-satellite payload project. Commercial off the Shelf (COTS) components are being used to implement the payload instrumentation. COTS components provide high processing performance, low power consumption, high reliability, low cost and are easily available. The main architecture of the system consists of commercially available Smartphone, FPGA (field-programmable gate-array) and microcontroller connected together along with sensors and telemetry systems.
Presently available smart phones are combination of multiple advanced sensors, different communication channels, powerful operating system and multi-core processors with large non-volatile memory. This also supports high resolution imaging devices for remote sensing application. The smart phone is interfaced to a microcontroller to expand its I/O to interface sensors and FPGA. FPGA supported high speed onboard parallel processing needs and complex controls. Flexible configurations for data acquisition system is provided using built-in A/D converters, counters and timers available in FPGA and microcontroller. The proposed system is an experimental balloon payload for monitoring atmospheric parameters like temperature, humidity, air pollution etc. This can also monitor city traffic, agricultural field and city landscape for security and surveillance.
Keywords: Tethered Balloon, Sensors, Payload, Smartphone, FPGA, Microcontroller
IJRET : International Journal of Research in Engineering and Technology is an international peer reviewed, online journal published by eSAT Publishing House for the enhancement of research in various disciplines of Engineering and Technology. The aim and scope of the journal is to provide an academic medium and an important reference for the advancement and dissemination of research results that support high-level learning, teaching and research in the fields of Engineering and Technology. We bring together Scientists, Academician, Field Engineers, Scholars and Students of related fields of Engineering and Technology.
Design of a usb based data acquisition systemeSAT Journals
Abstract
Development of a multi-channel compact data – acquisition board, which collects real world analog (0-5 Volt dc) and digital data,
delivers them to a personal computer using a USB communication link. The DAQ board is based on microchip PIC microcontroller
(PIC18F2550). A GUI is developed on Visual Basic which displays the instantaneous analog and digital data. It can also be used for
generating the control action signal (manual) which could be delivered to the actuator through a DAC through the microcontroller.
Keywords: PIC Microcontroller, data acquisition, USB.
1. Mobile Climate Control
Final Project Report
December 13, 2013
Michael McNair
Nathan Schaefer
Paul I. Lin, Class Instructor
Iskandar Hack, Project Advisor
ENGW 421 Technical Writing Project
Virginia A. Relph, Professor of English and Linguistics
Submitted to:
Paul I. Lin, Professor of ECET 491 Senior Design II
Department of Electrical and Computer Engineering Technology
College of Engineering, Technology, and Computer Science
Indiana University-Purdue University Fort Wayne, Indiana
2. ii
Abstract
This project is a conceptual design of a Mobile Climate Monitoring and Control application for
Android. It employs the use of a temperature sensor, a microcontroller, relays, and Bluetooth
communication, which will demonstrate a potential product that would enable control and
automation of comfort settings within a recreational vehicle or similar mobile living unit with a
computerized climate system.
Keywords:
Android – Java-based operating system for mobile devices
Microcontroller – computing device that manages input and output signals depending on
predetermined conditions
Relay – an electrically controlled switch that isolates low power devices from high current
Bluetooth – short-range wireless transmission standard used by low power devices for serial
communication
3. iii
Table of Contents
Abstract.........................................................................................................................................................ii
List of Illustrations........................................................................................................................................v
List of Tables ..............................................................................................................................................vii
Executive Summary...................................................................................................................................viii
Chapter 1: Introduction.................................................................................................................................1
Problem Topic...........................................................................................................................................1
Background...............................................................................................................................................1
Criteria ......................................................................................................................................................2
Methodology.............................................................................................................................................2
Primary Purpose........................................................................................................................................2
Overview...................................................................................................................................................3
Chapter 2: System Design Overview and Research......................................................................................4
Feasibility..................................................................................................................................................4
Design Process..........................................................................................................................................4
System Scope............................................................................................................................................4
Chapter 3: Hardware Design.........................................................................................................................5
The Microcontroller..................................................................................................................................5
Circuit Design...........................................................................................................................................6
Components ..........................................................................................................................................8
Arduino Shields ........................................................................................................................................8
Bluetooth Shield....................................................................................................................................9
Relay Shield........................................................................................................................................10
Chapter 4: Software Design........................................................................................................................13
Software Architecture .............................................................................................................................13
Android Software................................................................................................................................13
4. iv
Arduino Software................................................................................................................................14
Integrated Development Environment....................................................................................................15
Diagrams: UML, State, Activity.............................................................................................................17
Chapter 5: Unit Testing and System Integration.........................................................................................23
Software Testing and Validation.............................................................................................................23
Hardware Testing and Validation ...........................................................................................................29
System Integration, Testing, and Validation...........................................................................................29
Chapter 6: Project Management..................................................................................................................34
Schedule and Time Management............................................................................................................34
Resource and Cost Management.............................................................................................................35
Quality Management...............................................................................................................................37
Risk Management ...................................................................................................................................37
Lessons Learned......................................................................................................................................39
Chapter 7: Conclusion.................................................................................................................................41
Bibliography ................................................................................................................................................ A
Appendices................................................................................................................................................... B
Appendix A: Abbreviations ..................................................................................................................... B
Appendix B: Glossary.............................................................................................................................. D
Appendix C: Source Code ........................................................................................................................F
Android Classes (Activities) .................................................................................................................F
Android Layouts (XML Files)...........................................................................................................BB
Arduino Sketch (INO File) ............................................................................................................... GG
Appendix D: Datasheets ....................................................................................................................... OO
5. v
List of Illustrations
Figure 1 - Primary task of Bluetooth remote control
This diagram depicts the basic goal being able to control a light from a smartphone over
Bluetooth.
Figure 2 - Arduino Uno's major components
This is a top-view image of the Arduino Uno, with each of its main parts labeled.
Figure 3 - Hardware Schematic
This figure shows the interconnections of all the hardware components.
Figure 4 - Bluetooth Shield
This is an image of the SeeedStudio Bluetooth shield by itself.
Figure 5 - Grove Connectors
This is a close-up image of the Bluetooth shield’s Grove connectors.
Figure 6 - Left: Temp sensor and LED, Right: both connected to BT shield
The image on the left shows the temperature sensor module and the RGB LED module; the
image on the right shows those modules attached to the Bluetooth shield.
Figure 7 - Relays on shield
This picture shows all four relays positioned on the relay shield.
Figure 8 - Relay terminals
This is a close-up image of the relay shield’s connection terminals.
Figure 9 - Arduino and shields
These images are of the Arduino connected to the Bluetooth shield which is connected to the
relay shield.
Figure 10 - Screenshot of Android SDK Manager inside Eclipse IDE
This is a screen capture of the Android Software Development Kit manager installed in Eclipse.
Figure 11 - Android program UML
This is a UML diagram of all three classes (activities) that comprise the Android application.
Figure 12 - Android Activity Life Cycle
This diagram depicts each state that the Android application is in during its existence.
Figure 13 - Bluetooth State Diagram
This diagram shows the five different states in which the Bluetooth module operates.
Figure 14 - Application Flow Diagram (Top half)
This is the top half of a diagram of the Android application’s order of execution.
Figure 15 - Application Flow Diagram (Bottom half)
This is the bottom half of a diagram of the Android application’s order of execution.
Figure 16 - Android Application Interface
6. vi
This diagram shows the graphical layout of the Mobile Climate Control app.
Figure 17 - Mobile Climate Control app shortcut
This is a screenshot of the Samsung Galaxy SII phone’s home screen and the app shortcut.
Figure 18 - App Home screen
This screenshot shows the first screen that appears after launching the app.
Figure 19 - Bluetooth Dialog box
This screenshot shows the dialog box that prompts the user to turn on Bluetooth.
Figure 20 - Passcode entry box
This screenshot shows the app asking for a 4-digit PIN to pair the phone with the Bluetooth
shield.
Figure 21 - Manual Control screen
This screen capture is of the “Manual Control” screen; all buttons give direct, manual control.
Figure 22 - Automatic Control screen
This screenshot of the app shows the “Automatic Control” screen, which allows the user to input
a temperature at which the fan will automatically turn on, and if the toggle button is set to “On”,
the lamp will turn off at the same temperature.
Figure 23 - All components of assembly being tested
This is an image of preliminary testing to make sure all components of final unit operate by
Bluetooth control.
Figure 24 - Plywood base with bulb and Arduino stack
This is a picture of the first few pieces of hardware being added to the system.
Figure 25 - Plywood base with all high current wiring complete
This top-view image shows all the components of the hardware system wired and in place.
Figure 26 - Final Assembly with Lid on Hinges
This picture shows the interior of the final system.
Figure 27 - System with Lid Closed
This image is of the completed hardware unit with enclosure in place.
Figure 28 - Testing Final Assembly (receptacle)
This picture shows an Android phone with app being used to test the receptacle of the final
hardware.
Figure 29 - Testing Final Assembly (lamp)
This picture shows an Android phone with app being used to test the lamp of the final hardware.
7. vii
List of Tables
Table 1 - Projected Time and Resource requirements
This table shows what we planned to spend on the project.
Table 2 - Actual Time and Resource requirements
This table shows the actual amount of time and money spent on the project.
Table 3 - Gantt Chart of Scheduled Tasks
This table displays each portion of the project divided into subtasks and assigned a timeframe for
completion.
Table 4- Project Requirements
This table shows the original requirements for the project and whether or not they were met.
Table 5 - Risk Register
This table represents all of this risks we envisioned before starting the project and the severity,
consequences, and responses to each.
Table 6 - Risk Ranking Matrix
This table graphically lists the risks involved with the project, their likelihood, and their
influence on the final product.
8. viii
Executive Summary
The purpose of this project is to create a mobile phone application that makes possible the
convenient wireless control of temperature-influencing devices by integrating hardware and
software. The project was conceived in February 2013 and planned throughout the subsequent
weeks during the first phase of the Senior Design class. The project was forecast to be completed
by the week of December 9th
, the same year. The initial project concept was simply an Android
application with a button for turning a light on and off via a Bluetooth connection, but the idea
was further developed in the second phase of the Senior Design class to incorporate a more
definite, concrete application as a deliverable product. That final deliverable product consists of
two components: software and hardware. The software is in the form of an Android app, and the
hardware is a heat source, cooling mechanism, AC receptacle, and a temperature sensor all
integrated into a single unit to model the interior of a motor home or similar vehicle.
Keywords:
Android – Java-based operating system for mobile devices
Bluetooth – short-range wireless transmission protocol used by low power devices
Heat source – a compact 120 volt, 40 watt light bulb
Cooling mechanism – a 12 volt cpu fan
AC receptacle – 120 volt alternating current source for high current appliance
Temperature sensor – gathers interior temperature data and sends it to the Arduino for processing
Arduino – a type of microcontroller
Microcontroller – computing device that manages input and output signals depending on
predetermined conditions
9. 1
Chapter 1: Introduction
Problem Topic
Primarily, there needs to be a way to control an electronic device (such as a lamp or fan) from a
distance at which the device cannot be physically reached by the user. This remote control will
make adjusting interior temperature settings more convenient because it will allow interaction
with the system from virtually anywhere, provided the interior space does not exceed in radius
that of the Bluetooth range.
Figure 1 - Primary task of Bluetooth remote control
A second objective is to gain knowledge and experience with the Android mobile platform,
Bluetooth technology, and integrating with hardware components.
Background
It seems that most people have a smartphone on their person most of the time, which could be a
good, or a bad thing. But although it seems a smartphone can do just about anything, now they
will have the potential to be even more useful. This project is a conceptual model that represents
a system inside a vehicle that gives a user with an Android smartphone the ability to view
interior climate conditions, make adjustments, and set the program to automatically adjust
comfort settings based on the user’s preferences. The phone’s (or tablet’s) existing Bluetooth
technology would be employed to make the wireless connection with the system. This design is
10. 2
intended for use in recreational vehicles, but could be expanded to be included in other vehicles
such as boats.
Criteria
For our project to be successful, the following criteria must be met:
The mobile phone must be able to detect, pair, connect, and control the hardware over
Bluetooth.
The Android app must include an interface by which to control the hardware.
The Android app needs to be compatible with multiple OS versions and be no more than
15 megabytes in size.
The Bluetooth connection must be maintained at a distance of at least three feet.
The hardware assembly needs to be readily portable.
Methodology
The app we have created has a simple interface with a small number of buttons, while retaining
full functionality. The software will include the ability for the user to pair their phone with the
Bluetooth module and then allow the user to control the connected devices. The app was written
and debugged using the Eclipse Integrated Development Environment (IDE) Version 3.7.2 along
with the Android Software Development Kit (SDK). The Application Programming Interfaces
(APIs) that we included in the SDK are API 10 (Android 2.3.3), API 15 (Android 4.0.3), API 18
(Android 4.3), and API 19 (Android 4.4). We used the Arduino IDE Version 1.0.5 to write,
compile, and upload our test sketches and final sketch to the Arduino microcontroller chip.
The hardware assembly, which is designed to emulate a mobile living space, was created by
mounting the required components onto a piece of ¾ inch plywood and encasing it in a clear,
plastic container. The purpose of the encasement is two-fold: to make the assembly easily
portable and self-contained, and to provide a controlled environment for reading and regulating
internal temperature. The basic components of the hardware portion are: the Arduino assembly,
which consists of the Arduino Uno, a Bluetooth shield by SeeedStudio, and a relay shield also by
SeeedStudio stacked in that order bottom to top, a light bulb, CPU fan, household receptacle, and
wire [1].
Primary Purpose
One major benefit of this project is the opportunity for expanding the capability and functionality
of a smart device/vehicle relationship. This would mean the possibility of further design projects
relating to the initial concept and even branching out to other smart device applications. To
further bolster the product’s positive reception, a project to modularize it could be put in place.
11. 3
This would create a market for devices such as this beyond recreational vehicles—it could
expand to include any land vehicle or even a boat or plane. Standardization would make this
device compatible with virtually any vehicle, and widespread implementation would lead to
large orders and large profits.
Another benefit of this project is handiness. As long as someone in the vehicle has their
smartphone nearby, they can be aware of the indoor temperature. If it were too warm or humid,
the user would be able to change the vehicle’s climate setting to better suit them. An automatic
operation mode in the Android application would even give the user the added benefit of being
able to preset their preferences for comfort and allow the program to cycle the system on and off
depending on the user’s settings.
Overview
The system gives the user the ability to see what the temperature is within the vehicle, control the
system to adjust the comfort level, and preset the program to automatically make temperature
adjustments based on the user’s preferences. The system is designed to be modular, that is, it
would be compatible with virtually any mobile living space with an existing DC electrical
system. It would be a subsystem, deriving its power resources from the vehicle once installed.
For our project, the power will be supplied by standalone power supplies. To demonstrate our
system’s functionality via a simple conceptual prototype, the application will display interior
temperature and provide the user with control of a fan and a light bulb (heat source). This control
can be manual or automatic, depending on the user’s choice.
12. 4
Chapter 2: System Design Overview and Research
Feasibility
This project involves several different technologies, Bluetooth, Arduino, Android and a few
programming languages, Arduino Sketch and Eclipse Java. Putting all of this together is
demanding and time consuming. It is however possible to get all the parts working, with each
other, and performing to the specifications that are set out in the requirements. The time that it
takes to create the code and test it with the hardware that it is designed to be used with is more
than we had originally planned for, but with only a few exceptions we will have all requirements
met and /or exceeded. Such as the requirement for connection from 3 to 30 feet away, we are
able to connect and send/receive date from up to 70 feet with direct line of sight. The overall
concept of the app controlling the interior of an RV or other mobile home would also work if we
were to take it that far. The Arduino and the Bluetooth shield and relay shield are capable of
being connected into an existing infrastructure and combined with the existing components to
create a Bluetooth controlled comfortable living space. It would be similar to a home system that
uses the existing Wi-Fi in a home network for much the same purpose.
Design Process
Our original plan was to create an app that would be able to turn on and off a light attached to the
Arduino by using the built in Bluetooth on the phone. We wanted to get a better understanding of
both Bluetooth and smart phone app creation. Since the original idea we have updated the idea
and included a fan, then included an incandescent light. Then we had the idea of making it
control the temperature by monitoring it with an analog temp sensor and turning on a fan to cool
the sensor and using the light as a heat source. We also added the functionality of being able to
connect an air conditioner or other 120V devices with a relay shield. This way we can control
larger voltages and have on/off functionality for a variety of devices. We are now using the LED
as an indicator light since the lights that are built into the Arduino are too small to see clearly and
most of them are covered by the shields.
System Scope
The scope of this project is:
Android App
Bluetooth connection with Arduino microcontroller
Devices connected to the Arduino microcontroller
Arduino program to operate connected devices
Will not include designing of the Bluetooth hardware
Will not include designing or creating of the PCB to connect the hardware
13. 5
Chapter 3: Hardware Design
The Microcontroller
A microcontroller is a computing device that consists of three major components:
Inputs – electrical channels that allow logical information to enter the system from
external devices such as sensors, switches, and clock pulses.
Processor – the brain of the system that sees what data is coming into the system and
responds to it according to what preset instructions it has been given by the user.
Outputs – electrical channels that carry current to output devices such as lights, relays,
and motors.
The Arduino Uno is one of a family of many variations of prototype microcontrollers [2]. Simply
put, a microcontroller is a small computer chip that receives electronic data at its inputs,
performs any necessary calculations on the data received, and delivers the resulting data as
electronic signals from its outputs to control or operate an electrical device. These inputs and
outputs can be analog or digital, as the Arduino is equipped to handle both. It has six analog
input pins denoted by the uppercase letter ‘A’, and 14 digital pins denoted by the letter ‘D’, that
can be configured as either input or output. Furthermore, six of the 14 digital pins can be set as
Pulse Wave Modulation (PWM) outputs, which provide a pulsating signal that can be adjusted to
256 different frequency values.
The chip that is the heart of the Arduino Uno is the Atmel® ATmega328P. It is an 8-bit, 20
MHz, CMOS microcontroller that consumes a low amount of power. Based on the RISC
architecture, it provides 1 kilobyte of EEPROM, 2 kilobytes of RAM, 32 kilobytes of
programmable flash memory, internal and external interrupts, 23 inputs and ouputs, three timers,
and is programmable by USART over 2-conductor serial interface (USB). The chip can be
comfortably powered by 5 volts as its operating supply voltage range is 1.8 to 5.5 volts [3].
The Arduino Uno is fairly small and inexpensive, but it is still quite powerful considering its size
and cost. It creates a footprint of approximately two by three inches and weighs on the order of
just a few ounces. The board is a standard PCB (printed circuit board) and is covered by an array
of resistors, capacitors, ICs (integrated circuits), and LEDs as shown in Figure 2 below. The Uno
receives power from a power connector or from its USB connection.
14. 6
Figure 2 - Arduino Uno's major components
The main component of the board is the processor chip. The chip is told what to do with any
inputs it is given by computer instructions in the form of a simple computer program. The
program, or sketch, written in the programming language C++, is uploaded to the chip via a USB
cable from the computer on which the program was compiled. This action effectively customizes
the microprocessor chip to perform a specific task or set of tasks. The sketch will be covered in
more detail later.
Circuit Design
For our project there was no extensive circuit design. Most of the pieces that comprise the
system are modularized, which will be explained in the next section about shields. The only
hardware design involved was that of the selection, layout, and assembly of the physical
components that make up the composite unit which transmits and receives radio signals to and
from the Android phone. The interconnections of the system components can be seen in the
schematic diagram below.
15. 7
120VAC
@60Hz9VDC
DC In
D1
D0
D3
D2
D4
D5
D6
D7
D8
D9
D10
D11
D12
GND
5V
A0
A1
A2
A3
A4
A5
ArduinoUnoµController
Relay
U4
Relay
U3
Relay
U2
Fan
Lamp
Receptacle
Temp Sensor
RGB
LED
Bluetooth
Module
D13
GND
REF
7.5VDC
VIN
3V3
RESET
Figure 3 - Hardware Assembly Schematic
The large block is the Arduino Uno microcontroller chip. We configured the Arduino to receive
(Rx) data from the Bluetooth module on pin D3 and transmit (Tx) data to the Bluetooth module
on pin D2. By default, the Arduino is configured with pins D6 and D7 as the Rx and Tx pins,
respectively, but because the relays require the use of pins D4 – D7, the Rx/Tx pins had to be
reassigned.
The temperature sensor is connected to one of the Arduino’s analog inputs at pin A5. The RGB
LED is connected to digital pins D8 and D9, which are set as outputs. There are three relays used
in the circuit, each receiving coil-energizing current of 40 mA at 5 volts DC from pins D4 – D6.
The relay that controls the fan, labeled “U4” is connected to pin D4 of the Arduino. This relay,
when closed, allows 7.5 volts DC and 84 mA of current to power the fan. When relay “U3” is
activated by pin D5, it closes, allowing 120 volts AC and 0.5 A of current to flow through the 40
watt light bulb. When relay “U2” is energized by pin D6, the same 120 volt supply voltage
makes contact with the household electrical receptacle.
16. 8
Components
Arduino assembly
o Arduino Uno
o Bluetooth shield
o Relay shield
Rated for 3A each
40W bulb draws 0.33A
o Power adapter (outputs 9V / 1A)
20 gauge wire
o 2-conductor
o strand
14 gauge extension cable
o 2-conductor w/ ground
o with 3-prong connector
o strand
120V lamp base
40W bulb
(2) 120V / 15A receptacles
CPU fan
o 12V / 150mA
o Powered by power adapter
Outputs 7.5V / 100mA
Actual output is 7.8V / 84mA
15.5” x 11” ¾ inch plywood board
15.5” x 11” x 6” transparent, plastic container
Various bolts, nuts, screws, hinges, and brackets
Arduino Shields
The low voltage components of our hardware assembly, which consist of the microcontroller,
Bluetooth radio, relays, temperature sensor, and LED, are all modular in physical design. That
means that they are all designed to a specific standard to work with other equipment designed to
the same standard. For instance, the Arduino brand microcontroller module has been widely
accepted as a standard for designing devices and accessories that will seamlessly work with it.
Such devices are usually marked as “Arduino compatible” or some similar indication, and are
referred to as “shields”.
A shield is a simple way to connect a device to the Arduino and is a separate PCB with
application specific components on it and pins that perfectly match the pin holes of the Arduino
board. There are numerous shields available for many different applications such as WiFi, GPS,
and a keypad. We have taken advantage of two different types of shields for our circuit, both
17. 9
from SeeedStudio. Our system employs the use of a Bluetooth shield (Model SLD63030P) and a
relay shield (Version 1.2b) [4].
Bluetooth Shield
The Bluetooth shield hosts a Bluetooth module that is capable of V2.0+EDR 3Mbps Modulation
and includes a 2.4 GHz radio transceiver and baseband. Its normal reception sensitivity is -80
dBm and its maximum transmission power is +4 dBm. Being a Class 2 Bluetooth device, it is
rated as being capable of transmitting radio frequencies at a distance of about 10 meters, which is
roughly 30 feet [5]. Although this is a typical range specification, we have achieved a
communication distance of over double that.
Like many shields, the Bluetooth shield has pins on the bottom for connecting to the Arduino
and ports on the top for connecting another shield to it.
Figure 4 - Bluetooth Shield
Additionally, the Bluetooth shield includes two Grove connectors, one digital and one analog [6].
Grove connectors are four-pin connectors that make it easy to connect and disconnect sensors
and other devices to an Arduino. Special shields with these connectors can be attached to the
Arduino by which to conveniently connect many input and output devices.
18. 10
Figure 5 - Grove Connectors
The temperature sensor and RGB LED we used in the system are attached to the Arduino by
Grove connectors; the LED is connected to the digital connector and the temperature sensor to
the analog one. The temperature sensor’s range of sensitivity is between -40 and125 degrees
Celsius (-40 and 257 degrees Fahrenheit) with an accuracy of ± 1.5 degrees.
Figure 6 - Left: Temp sensor and LED, Right: both connected to BT shield
Relay Shield
The relay shield houses four relays, each of which is rated for 3 amps of current at 120 volts AC
or 24 volts DC [7]. Their maximum switching voltage is 240 volts AC or 60 volts DC and
maximum switching current is 5 amps. These relays are rated to last for 10 million switching
operations, which will hopefully be enough for our project!
19. 11
Figure 7 - Relays on shield
All the relays have three terminals: one common terminal (labeled “COM”) where we have
attached the “hot” wire from the high voltage circuit, a normally closed terminal (labeled “NC”)
which we do not use, and a normally open terminal (labeled “NO”) which we connect to the hot
wire terminal of the appliance the relay is sourcing.
Figure 8 - Relay Terminals
If the Arduino is being powered by its dedicated 9 volt power supply, the relay shield’s power
input is not needed, but if the Arduino is powered by USB, the relay shield must be powered.
20. 12
In form, the relay shield is a top-most type of shield in that it has no pin terminals for additional
shield reception or input/output connection.
Figure 9 - Arduino and shields
This was not a big problem for our project because there were no further essential components to
be connected to the Arduino. Most of the output devices are controlled by relays. However, it did
force us to modify our original plan of using the Arduino’s PWM output capabilities to control
the fan’s revolution speed. Besides being practically more feasible to run the fan via a relay,
testing the fan at various speeds controlled by PWM output of the Arduino proved that the
system’s purpose could be achieved with a single fan speed. Also, running the fan at a speed less
than that from full voltage resulted in instability and high-pitched squealing sound.
21. 13
Chapter 4: Software Design
Software Architecture
There are two aspects of software architecture to our system: that for the mobile phone
application, and the program that runs the Arduino microcontroller. The mobile phones that we
are using are our own personal smartphones. Nathan’s phone is a Samsung Galaxy SII (Model
SPH-D710) and runs Android Version 4.0.4. Mike’s phone is a Samsung Galaxy S4 (Model
SPH-L720) and runs Android Version 4.3.
Android Software
The phone app is a Java program which incorporates Android components through imports into
the program package. Below are some of the Android imports used in our app.
package com.example.mobilecc;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
These are used to support Android-specific application requirements such as text fields, buttons,
and layouts. Just as all Java programs are actually within class files, the Android program resides
in classes as well. In Android programming however, the class is an activity. The program can
have multiple activities, as ours does, and can be launched when the user starts the application.
Our application contains three activities: MainActivity, ManualActivity, and AutoActivity. Each
of those activities represents a different screen in the app and the graphical format of each is
configured using layout XML files, one associated with each activity. In fact, XML files are used
to hold string values for use throughout the program and the Android Manifest File, which
contains program information such as Android version support, permissions, and included
activities (with parent relationships if applicable).
The MainActivity activity is the first thing that launches when the app is started. When launched,
the onCreate() method creates an instance of the program and then it becomes visible to the user.
The sole practical purpose of the MainActivity class is to give the user the option to choose
between manual and automatic control of the remote devices. These two options are represented
by two buttons on the screen. When the user pushes either button, an intent, or action to be
22. 14
performed, is created and then executed. The intents in our application start the other two
activities, the ManualActivity activity and the AutoActivity activity.
The ManualActivity activity contains the software required to negotiate and establish a Bluetooth
connection between the host device (Samsung phone) and the remote device (Bluetooth shield).
It also includes a text field to display temperature received from the temperature sensor and
toggle buttons to turn the fan, lamp, and receptacle on and off. When the ManualActivity activity
is started, it checks to see if Bluetooth is available and turned on. If it is available, but turned off,
the application will prompt the user to turn it on. If the Bluetooth shield is not yet paired, it will
prompt the user to enter a passcode.
The AutoActivity activity is very similar to ManualActivity in that it facilitates a Bluetooth
session and displays temperature on the screen. What makes it different is that it allows the user
to enter a two-digit temperature value in degrees Fahrenheit which will tell the Arduino at what
temperature the fan should turn off. In addition, the toggle button on the screen can be turned on
so that if the fan comes on, the heat source (lamp) is turned off. While either AutoActivity or
ManualActivity are running, they are “listening” for incoming temperature data from the phone’s
Bluetooth module. If any data is received, the characters representing the temperature are
handled by a handler object in the activities’ onCreate() method. The handler takes each
character, one at a time, and appends each to the end of a StringBuilder (a sequence of
characters), to be displayed as the multi-digit temperature value.
Arduino Software
Our Arduino program makes use of the microcontroller’s digital and analog pins. The sketch’s
opening portion contains the declarations and definitions of pins. Digital pins 2 through 9 are
used, as are analog pins 1 and 5. Arduino sketches are two-part programs: there is the Setup
function and the Loop function [8]. Within the Setup function, serial communication is started at
a baud rate of 9600 bits/sec and the Bluetooth shield is initialized. Also, all of the pins declared
in the beginning of the sketch are assigned as either input or output.
In the Loop function, the program reads the data from the temperature sensor and performs
calculations to convert it into an integer value in degrees Fahrenheit.
a = temperature received from sensor (integer)
r = resistance (double)
c = temperature in Celsius (double)
f = temperature in Fahrenheit (double)
r = (1023 – a) * (10,000 / a)
c = 1 / (log (r / 10,000)) / ((3975 + (1 / 298.15)) – 273.15)
f = c * 9 / 5 + 32
f(int) = f cast to integer
23. 15
Next, the program sends the converted temperature value over Bluetooth to the connected
Android phone. It also checks if the temperature received is greater than the maximum
temperature required to turn the fan on. If the received temperature is higher than the threshold
temperature and the Automatic Mode button on the phone is set to “On”, the fan should turn on
the lamp should turn off. Otherwise, if Auto Mode is set to “Off”, the lamp remains on.
Continuing in the Loop function, the program checks if any command has been sent from the
phone to activate or deactivate one of the relays, and ultimately, one of the connected electrical
devices. If so, it turns on the appropriate device accordingly.
Integrated Development Environment
Our Android app is a Java application that was developed using the Android Software
Development Kit (SDK). We installed the necessary Application Programming Interfaces (APIs)
to support the versions of Android installed on our respective phones, which included API15 (to
support Android 4.0.3) and API18 (to support Android 4.3). See image below.
24. 16
Figure 10 - Screenshot of Android SDK Manager inside Eclipse IDE
Code writing, debugging, editing, and layouts were done with Eclipse Integrated Development
Environment (IDE) Version 3.7.2 with the additional installation of the Android SDK. The
ObjectAid Class Diagram plug-in was also installed to assist with creating Unified Modeling
Language (UML) diagrams.
27. 19
+BTSTATE: 0
+BTSTATE: 1 +BTSTATE: 3
+BTSTATE: 2
+BTSTATE: 4
Arduino is
Powered On
Bluetooth is initialing
Bluetooth is inquiring
Bluetooth is disconnected
Bluetooth is
connecting
Bluetooth is connected
Figure 13 - Bluetooth State Diagram
28. 20
‘Mobile Climate
Control’ Screen is
displayed
Start
‘Manual Control’
Button is pushed
‘Auto Control’
Button is pushed
Turn
Bluetooth on?
Is device
paired?
Yes
Yes
No
No
‘Manual Control’
Screen is
displayed with no
functionality
User enters
PIN to pair
A B C
Figure 14 - Application Flow Diagram (Top half)
29. 21
‘Auto Control’
Screen is
displayed
Fan changes
states
User
enters
a temp
Lamp
remains on
regardless of
temp
Lamp turns
off when
temp reaches
selected level
‘Fan Control’
Button is pushed
User navigates
back
User exits
program
End
Temperature
is displayed
on screen
Lamp
changes
states
‘Lamp Control’
Button is pushed
Receptacle
changes
states
‘Receptacle
Control’ Button is
pushed
‘Manual Control’
Screen is
displayed
Is ‘Auto
Mode’ ON?
Yes
No
A B C
Figure 15 - Application Flow Diagram (Bottom half)
30. 22
Mobile Climate Control
Screen 1
Manual Control
Automatic
Control
Turn Bluetooth on?
Okay
Cancel
Dialog Box 1
Indoor Temp:
74 °F
Manual Control
Screen 2
Indoor Temp:
74 °F
Fan Control
On/Off
Screen 3
Indoor Temp:
74 °F
Set temperature threshold
for fan operation:
° F
Automatic Mode (Lamp
turns off when fan turns on.)
Enter 4-digit PIN:
Okay
Dialog Box 2
On/Off
On/Off
Lamp Control
Receptacle Control
Automatic Control
On/Off
Figure 16 - Android Application Interface
31. 23
Chapter 5: Unit Testing and System Integration
Software Testing and Validation
The Android application compiles successfully and installs on the Samsung
Galaxy SII phone without any problems. We even created a custom icon for
the app home screen shortcut.
The first step to testing the app is selecting it from the home screen as shown below.
Figure 17 - Mobile Climate Control app shortcut
32. 24
After launching the app, the home screen will appear, displaying two buttons that will open a
“Manual Control” screen and an “Automatic Control” screen, respectively.
Figure 18 - App Home Screen
33. 25
The next thing that
appears on the screen
is a dialog box that
requests the user to
turn on Bluetooth. If
“Yes” is selected,
Bluetooth is turned
on, if “No” is
selected, Bluetooth is
not turned on but the
app will continue
with no connectivity.
Figure 19 - Bluetooth Dialog Box
34. 26
Next, if the Bluetooth shield is not yet paired with the phone, another box appears asking the
user to enter a four-digit passcode to pair with the device.
Figure 20 - Passcode entry box
35. 27
At this point, as long Bluetooth is on and pairing is complete, the app’s manual control screen is
displayed. The temperature is shown in degrees Fahrenheit and there are three toggle buttons
which can be pressed to manipulate three different devices.
Figure 21 - Manual Control Screen
36. 28
If the user pushes the back key on the phone (if the phone has one) or presses the integrated back
arrow at the top of the app screen, the app home screen will be displayed again. If the automatic
control button is pressed, the automatic control screen will appear, giving the user the option to
set the lamp to turn off when the fan is running.
Figure 22 - Automatic Control screen
37. 29
Hardware Testing and Validation
As each part of the hardware was connected we tested to make sure that the code we already had
would still work with it. At first we only had the Arduino Uno and the Bluetooth shield and were
able to communicate with them from the phone. They were programmed from our computer and
then powered from a power outlet. To allow for adding more components at a future time we
also have the three prong household receptacle that can be powered on/off through the use of the
relays. There is also one relay that is left open at this time that will allow for expansion of the
module at a later date. The figure below shows the testing of the entire assembly of the module,
with everything turned on.
Figure 23 - All components of assembly being tested
System Integration, Testing, and Validation
Hardware assembly and fabrication was done over the course of two days; about seven hours
was spent on the development, construction, and wiring of the final unit, and then it was tested
for a few hours after construction was complete. The first part of the assembly was a 15.5” x 11”
piece of ¾ inch plywood, sanded and rounded smooth. The size of the footprint was determined
by the size of the clear plastic container used to enclose the system.
38. 30
After holes were cut in the end of the plastic container for the fan, it was mounted to it with the
provided screws. Then, the Arduino/shields combo was seated on a piece of corrugated
cardboard serving as a shock mount and attached to the board opposite the fan with screws. A
make-shift bracket was shaped and attached in a position above the light bulb socket on which
the temperature sensor was mounted. Another bracket was used to mount the LED in the corner
of the container. See Figure 24 below.
Figure 24 - Plywood base with bulb and Arduino stack
The next thing to do was to bring 120 volts AC into the unit. The initial idea for powering all the
components was to have each power adapter plug into a power strip and enter the system
individually. But instead, for the sake of neatness and professionalism, we included a second AC
receptacle inside the container to supply power to the fan and Arduino elements. From that
receptacle, a parallel connection was made to power the 40 watt bulb and controlled exterior
receptacle. By using this second receptacle, which serves as a junction box, both of the power
adapters remain enclosed and out of the way and only one power supply cable is needed. See
Figure 25 below. The clear, plastic container used to enclose the system for the purpose of
concealment and temperature control was mounted to the plywood board using two small hinges
and two small screws. That way, if access is needed, only two screws must be removed and it
will prop open slightly (see Figure 26).
39. 31
Figure 25 - Plywood base with all high current wiring complete
Figure 26 - Final Assembly with Lid on Hinges
40. 32
Figure 27 - System with Lid Closed
After the assembly was complete, it was time to test it to make sure it worked! Plugging it into
the wall for the first time made for a slightly tense moment, we did not want to see sparks or
smoke. Thankfully, it worked well right away. All of the hardware functioned perfectly. The
only imperfection was a few minor software bugs that were yet to be worked out.
Below are some images of testing the final assembly with one of the Samsung phones. The 40
watt bulb and the receptacle functioned perfectly under the Mobile Climate Control app’s
Manual Mode, but the fan malfunctioned unless it was operated under Automatic Mode, one of
the bugs mentioned earlier.
41. 33
Figure 28 - Testing Final Assembly (receptacle)
Figure 29 - Testing Final Assembly (lamp)
42. 34
Chapter 6: Project Management
Schedule and Time Management
Below are tables of the projected time and resources and actual time and resources used.
Table 1 - Projected Time and Resource requirements
Item Quantity Cost Total Task Mike Nathan Total
Android Books 3 $45.00 $45.00 Design System 5.0 5.0 10.0
Tools 1 $40.00 $40.00 Create schematic 1.5 1.5 3.0
Bluetooth Module 1 $100.00 $100.00 Select Required Components 1.0 1.0 2.0
Order Parts 0.5 0.5 1.0
Total $185.00 Design Software Architecture 2.0 2.0 4.0
Develop Software 3.0 3.0 6.0
Write Code 15.0 15.0 30.0
Debug Code 30.0 30.0 60.0
Assemble Components 7.5 7.5 15.0
Test Assembled Prototype 8.0 8.0 16.0
Verify System 15.0 15.0 30.0
Write Report Outline 2.0 2.0 4.0
Write Report Draft 3.0 3.0 6.0
Write Final Report 1.0 1.0 2.0
Create Presentation Outline 2.0 2.0 4.0
Create Presentation Draft 4.0 4.0 8.0
Create Final Presentation 2.0 2.0 4.0
Total 102.5 102.5 205.0
Material Labor (hours)
PROJECTED COSTS
43. 35
Table 2 - Actual Time and Resource requirements
Item Quantity Cost Total Task Mike Nathan Total
Android Books 3 $15.00 $45.00 Research 17.0 13.0 30.0
Arduino Uno 3 $27.95 $83.85 Design System 5.0 4.0 9.0
Relay Shield 2 $19.99 $39.98 Create Schematic 1.5 1.5
Bluetooth Shield 3 $21.75 $65.25 Select Required Components 3.0 3.0
Grove 4-pin cable 1 $4.80 $4.80 Order Parts 0.5 1.0 1.5
Grove RGB LED 2 $3.80 $7.60 Design Software Architecture 1.0 1.0
Grove Temp Sensor 2 $2.80 $5.60 Develop Software 12.0 2.5 14.5
USB Cable 2 $2.95 $5.90 Write Code 6.0 10.0 16.0
Power Supply 2 $13.95 $27.90 Debug Code 6.0 26.0 32.0
TIP31 Transistors 10 $0.29 $2.90 Assemble Components 4.0 7.5 11.5
1KOhm Resistors 10 $0.10 $0.99 Test Assembled Prototype 15.5 20.5 36.0
22AWG Solid Wire 1 $7.95 $7.95 Verify System 5.0 2.5 7.5
60W Light Bulb 1 $0.00 $0.00 Write Report Outline 3.0 1.0 4.0
Light Fixture 1 $0.00 $0.00 Write Report Draft 10.0 21.0 31.0
AC Receptacle 1 $0.00 $0.00 Write Final Report 1.5 5.5 7.0
CPU Fan 1 $0.00 $0.00 Create Presentation Outline 2.0 2.0
$0.00 Create Presentation Draft 5.0 5.0
$0.00 Create Final Presentation 13.0 0.5 13.5
$0.00 0.0
$0.00 0.0
$0.00 0.0
$0.00 0.0
Total $297.72 Total 105.5 120.5 226.0
ACTUAL COSTS
Material (dollars) Labor (hours)
Resource and Cost Management
The total cost we planned for the project was $185. That figure was based on the projected costs
of one set of hardware components, tools, and resource books. We ordered enough components
to build two working projects for the sake of redundancy in case there were any hardware defects
or mistakes.
The actual total cost spent on hardware thus far is $297.72, which is $112.72 over budget. One
reason for going over budget is that half of the major parts (one of the Arduinos and Bluetooth
shield) were ruined and needed replaced. Another reason for overspending is the redundancy of
material procured for the project assembly. If that redundancy is taken into consideration (at least
two of each component was ordered), that brings the price per finished unit to $148.86, which is
$36.14 under the forecasted hardware cost. So, overall, the project was 61% over budget, but
based on the cost of one finished working unit, the project was 20% under budget.
The total number of hours spent on the project so far is approximately 226 hours.
45. 37
Quality Management
For quality management we have kept close to what our requirements state and added in
functionality to make the project better. In doing so we have expanded the scope and changed
what the app is doing. To keep the quality of work consistent we have been testing every step of
the way and changing the design and layout of our app to look better and be more functional. We
have also redesigned the Arduino code to be more efficient in it execution.
Table 4- Project Requirements
ID# Requirement
Inspect,
Analyze, Demo
or Test
Status (Pass/Fail)
Operational Requirement
1 The mobile phone application shall remotely control an electronic device via Bluetooth. Demo Pass
2 The application UI shall give the user options to monitor and control a connected Bluetooth device. Demo Pass
Performance Requirements
1 The device shall have a wireless range of 3 feet. Test Pass
2 The device should have a wireless range of 30 feet. Test Pass
3 The application should run on other versions of Android. Analyze Pass
4 The application should be able to pair with 3 devices simultaneously Test Pass
5 The application shall remember previously paired devices. Test Pass
Physical Characteristics Requirements
1 The system housing the software shall be a portable, hand-held device. Inspect Pass
2 The remote side of the system shall be portable. Inspect Pass
3 The size of the software installation shall be less than 15 MB. Inspect Pass
4 The size of the software installation should be less than 5 MB Inspect Pass
5 The Bluetooth module should be of version 3.0 or higher. Inspect Fail
Utilization Environment Requirements
1 The system will be designed for indoor use only Demo Pass
2 The system shall be designed for a range of 3 feet in line of sight. Demo Pass
3 The application shall run on a version of Android between 4.0 and 4.0.4. Analyze Pass
4 The application shall run on an Android phone: HTC EVO Design Demo Pass
5 The application should be able to run on other Android phones Demo Pass
Functional Requirements
1 The application shall allow the user to issue instructions (on, off) via Bluetooth from mobile phone to paired device. Demo Pass
2 The application shall allow the user to monitor parameters (on, off) of remote device. Demo Pass
3 The application should save connection setting for known devices. Demo Pass
Risk Management
Risk management has proven to be a difficult task, mostly because of the amount of time that we
both have to work on the project, and the time of day that we work on it. Michael blew up his
Arduino and Bluetooth shield by crossing wires and sending 120V through them. That was an
unforeseen problem and those components had to be replaced.
46. 38
Table 5 - Risk Register
ID
Entry
Date
Risk Description Consequence of Risk Status
Likelihood
(1-5)
Severity
(1-5)
Score Rank*
Response
(Accept, Avoid, Transfer, Mitigate plus
description)
1 25-Mar-13
May not complete the
coding in one semester -
s
Cannot deliver product,
not fully functioning
demo
Closed 2 5 10 Medium
Mitigate: begin research now, testing code
writing, Avoid: scale back functions
2 25-Mar-13
Integration takes longer
than scheduled - t
can't get operational
prototype by the end of
semester
Open 3 4 12 Medium
Mitigate: will require more man hours to
recover schedule at the expense of cost
3 25-Mar-13
Cost of Bluetooth
module exceeds budget
- c
More out of pocket Closed 3 3 9 Medium
Avoid: look for cheaper module or increase
budget from original plan
4 25-Mar-13
Integration requires
more man hours than
planned - s
Costs exceed planned
budget
Open 3 3 9 Medium
Accept: spend more time than originally
planned
5 25-Mar-13
Wireless range does
not reach 30 feet - s
Demo does not meet
range requirement
Closed 2 1 2 Low
Accept: remote Bluetooth device will be
placed closer to connected phone
6 29-Mar-13
Android development
tools are not free as
expected - c
More out of pocket
expense
Closed 1 4 4 Low
Accept: we would still have to buy the
development tools to program for Android
OS
7 29-Apr-13
App cannot pair with
multiple devices
simultaneously - s
Can only connect to
one device at a time
Open 1 1 1 Low
Accept: if it cannot connect to more than
one device at a time we will focus on just
one device
8 29-Apr-13
Computer crashes,
deleting program - s
Program will have to be
rewritten
Closed 2 5 10 Medium
Avoid: backup the program to external
storage on a regular basis
9 29-Apr-13
App does not work on
intended phone - s
Will not be able to
demonstrate app on
smart phone
Open 1 3 3 Low
Mitigate: buy a Bluetooth dongle to use
the emulator on the computer
10 29-Apr-13
App does not store
previously paired
devices - s
Convenience of
reconnecting to a
previously paired device
will be lost
Open 2 3 6 Low
Mitigate: will put more man hours into
fixing the program error
11 29-Apr-13
App is larger than 15
megabytes - s
App will take longer to
install and consume
more phone memory
Closed 3 1 3 Low
Accept: leave program code as is if app is
functions correctly
47. 39
Table 6 - Risk Ranking
1
Insignificant:
minor
problem
easily
handled by
day to day
processes
2
Minor:
some
disruption
possible
3
Moderate:
significant
time /
resources
required
4
Major:
operations
severely
damaged
5
Catastrophic:
project
survival is at
risk
5
Almost Certain:
>90% chance
5 10
4
High:
50 - 90% chance
4
3
Moderate:
10 - 50% chance
3 3,4 2
2
Unlikely:
3 - 10% chance
2 5 1,8
1
Rare:
<3% chance
1 7,9 11 6
1 2 3 4 5
Likelihood
Severity
Risk Ranking
These two figures depict the original scores that we gave to the risks that we came up with. As
you can see there is one for crashing our computer, which happened when Michael crossed the
wires. There was not one for blowing up the boards however and so it was not addressed before
hand. We attempted to mitigate the risk by purchasing two sets of everything so that we would
both have a working set when we were all finished. It was overcome by purchasing a third set
once the first was destroyed. This did however set Michael back several days, but it also allowed
for more research and code testing in emulators.
Lessons Learned
Michael learned to be more careful when working with 120V. Crossing the wires and blowing up
the boards was not a good move. Nathan learned that doing more research and getting familiar
48. 40
with the Android platform and Arduino technology earlier in the project would have made it less
stressful and easier to stay on schedule.
Also we learned that there are many possibilities for what can be created with Arduino. We have
a better understanding of Bluetooth technology and how to use it. We have learned how to
manage a project that spans a period of time greater that a few months and to complete the
overall project by setting smaller tasks that are more manageable.
49. 41
Chapter 7: Conclusion
In conclusion, we have learned a lot from this project. In coming up with a way to control the
temperature inside a RV, we have learned that there are a lot of possibilities for a mobile app.
Our original idea was just to control a light switch or a receptacle and have it turn a light on or
off. As we progressed through last semester and this one, we found that that was not enough. It
would not have pushed us to come up with a worthwhile project. After taking the advice of
several professors we added to the project. First we added the capability for controlling multiple
devices, then added fans, lights, and a temperature sensor. And for that we created an app that
will allow a user to control the comfort level inside a motor home. With this app and the module
that we created with it you can turn on the light (heat source) and warm up the place or turn on
the fan (A/C unit) to cool it down. Or you can program in a temperature you want to keep and
the module will do the calculations for you and monitor the temperature and turn the other
devices on and off as necessary.
51. B
Appendices
Appendix A: Abbreviations
A – amp
A/C – Air Conditioning
AC – Alternating Current
API – Application Programming Interface
CMOS – Complementary Metal Oxide Semiconductor
COM – Common
CPU – Central Processing Unit
DC – Direct Current
dBm – Decibel of Power in reference to One Milliwatt
EDR – Enhanced Data Rate
EEPROM – Electrically Erasable Programmable Read-Only Memory
GHz – Gigahertz
GPS – Global Positioning System
IC – Integrated Circuit
IDE – Integrated Development Environment
LED – Light Emitting Diode
mA – milliamp
Mbps – Megabits Per Second
MHz – Megahertz
NC – Normally Closed
NO – Normally Open
PCB – Printed Circuit Board
PWM – Pulse Wave Modulation
RAM – Random Access Memory
RGB – Red Green Blue
RISC – Reduced Instruction Set Computing
52. C
RV – Recreational Vehicle
Rx – Receive
SDK – Software Development Kit
Tx – Transmit
USART – Universal Asynchronous Receiver/Transmitter
USB – Universal Serial Bus
V – volt
W – watt
Wi-Fi – Wireless Fidelity
XML - Extensible Markup Language
UML – Unified Modeling Language
53. D
Appendix B: Glossary
Activity – the structural component of an Android program that represents an instance of the app
Analog – a continuous signal type with no discrete values or changes
Android – a mobile operating system brand by Google, used mostly for smartphones and tablets
Android Manifest – a file in an Android program that contains program information such as
Android version support, permissions, and included activities
App – a small, simple software program, usually designed for mobile device use
Application – a piece of software designed to accomplish a particular task
Arduino – a brand of microcontroller kit that is quite user friendly and for which is easy to
develop
Assembly – also referred to as construction and unit, is the final combination of physical
components that make up the hardware portion of the system
ATmega328P – model of microcontroller chip on the Arduino Uno
Atmel – the company that makes the microcontroller that resides on the Arduino Uno
Bluetooth – short-range wireless transmission standard used by low power devices for serial
communication
Bug – an arrangement of code in a computer program that causes it to behave in an undesirable
manner
C++ – an object-oriented programming language used to write software for the Arduino
Connect – to establish a Bluetooth transmission session
Digital – a non-continuous signal type characterized by definite values and states
Eclipse – a program in which software code can be written, debugged, and compiled
Galaxy S II and 4 – phone models in order starting with the older one
Grove – a simple connection standard by which devices and sensors can be attached to the
Arduino
Hardware – physical and tangible components of the project system
Import – the programming convention for including outside classes in the project
Incandescent – a light source resulting from a heated filament
Java – an object-oriented programming language used to write software for Android systems
54. E
Kilobyte - equal to one thousand bytes, or 8 thousand bits, each of which is a zero (0) or a one
(1)
Loop – the second part of the Arduino sketch in which all the functions and conditional
statements are executed
Microcontroller – computing device that manages input and output signals according to
instructions included in installed program software
Relay – an electrically controlled switch that isolates low power devices from high current
devices
Software – non-physical, intangible components of the project system that control system logic
Pair – the act of a Bluetooth master device such as a phone saving device information of a slave
Bluetooth device
Megabyte – equal to one million bytes, or 8 million bits, each of which is a zero (0) or a one (1)
Pin – a physical and electrical connection to the microcontroller chip
Remote – at a distance out of human reach
Samsung – phone manufacturer
SeeedStudio – maker of the Bluetooth and relay shields
Setup – the first part of the Arduino sketch in which serial communication is initialized and I/O
pins are declared
Shield – an add-on component with a specific function such as Bluetooth, compatible with
Arduino
Sketch – a small-sized software program that is installed and run on the Arduino microcontroller
which contains two parts: Setup and Loop
Uno – of the smaller models of Arduinos available
55. F
Appendix C: Source Code
Android Classes (Activities)
“MainActivity.java”
/*
* Course: CPET491 - Senior Design Phase II
* Title: Mobile Climate Control (MobileCC)
* Members: Michael McNair and Nathan Schaefer
* Date: 12/13/13
* File: MainActivity.java
* Description: This class is the app's main class. It
* contains two Buttons; one creates
* an intent which launches the activity
* "ManualActivity" and the other creates
* an intent which launches the activity
* "AutoActivity".
*/
// Program package
package com.example.mobilecc;
// Imports
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
// MainActivity class which extends the Activity class
public class MainActivity extends Activity {
// Declarations
private Button manualBtn; // This button is associated with the
// "ManualActivity" activity
private Button autoBtn; // This button is associated with the "AutoActivity"
// activity
// The main method of the class. It is responsible for creating an instance
// of the "MainActivity" activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Creates connection between
//
this class and its layout XML
//
file
56. G
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Locks
// the
// app
// into
// portrait
// orientation
// New Objects
manualBtn = (Button) findViewById(R.id.manualButton); // Creates a new
// button called
// "Manual Control"
autoBtn = (Button) findViewById(R.id.autoButton); // Creates a new
// button called
// "Automatic Control"
// When "Manual Control" button is pressed, an intent to start a new
// activity called "iMan" is created and launches "ManualActivity".
manualBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent iMan = new Intent(getApplicationContext(),
ManualActivity.class);
startActivity(iMan);
}
});
// When "Automatic Control" button is pressed, an intent to start a new
// activity called "iAuto" is created and launches "AutoActivity".
autoBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent iAuto = new Intent(getApplicationContext(),
AutoActivity.class);
startActivity(iAuto);
}
});
}
// This method creates a menu to which application options can be added.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu); // Inflate the menu; this
57. H
// adds items to the
// action bar if it is
// present
return true;
}
}
“ManualActivity.java”
/*
* Course: CPET491 - Senior Design Phase II
* Title: Mobile Climate Control (MobileCC)
* Members: Michael McNair and Nathan Schaefer
* Date: 12/13/13
* File: ManualActivity.java
* Description: This class is the app's manual control class.
* It contains a TextView, three ToggleButtons,
* and a message handler. The TextView displays
* the indoor temperature value received and
* manipulated by the handler from the sensor
* connected to the Arduino. Each of the
* ToggleButtons controls a different device:
* one for the fan, one for the lamp, and one
* for the receptacle. The message handler
* receives the incoming characters, appends them,
* and displays their value in the TextView.
* Within this class, a Bluetooth connection is
* created, which includes initiating a
* BluetoothAdapter and BluetoothSocket.
*/
// Program package
package com.example.mobilecc;
// Imports
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.ActivityInfo;
58. I
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
// ManualActivity class which extends the Activity class
public class ManualActivity extends Activity {
// Declarations
private ToggleButton fOnOffButton; // This ToggleButton is associated with
// the fan control
private ToggleButton lOnOffButton; // This ToggleButton is associated with
// the lamp control
private ToggleButton rOnOffButton; // This ToggleButton is associated with
// the receptacle
control
private TextView tempDisplay; // This TextView is associated with the
// displayed temperature
private Handler h; // This handler is associated with receiving incoming
// characters
private BluetoothAdapter btAdapter = null; // Represents the host phone's
//
physical Bluetooth adapter
private BluetoothSocket btSocket = null; // Initiates and controls the
//
Bluetooth connection
private static final String TAG = "Bluetooth"; // Final string called
// "Bluetooth"
final int RECEIVE_MESSAGE = 1; // Status for Handler
private ConnectedThread mConnectedThread; // An object of the
//
"ConnectedThread" class that
//
manages input and output of
//
data
private StringBuilder sb = new StringBuilder(); // A dynamic sequence of
// characters used for
// assembling the
// temperature value
// Serial Port Profile (SPP) Universally Unique Identifier (UUID) service
private static final UUID MY_UUID = UUID
59. J
.fromString("00001101-0000-1000-8000-00805F9B34FB"); // This is
the
// unique ID
// of the
// Bluetooth
// shield
// MAC address of Bluetooth module
private static String address = "00:13:EF:00:07:87"; // SeeedStudio
// Bluetooth shield
// MAC address
/** Called when the activity is first created. */
@SuppressLint("HandlerLeak")
// The main method of the class. It is responsible for creating an instance
// of the "ManualActivity" activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual);// Creates connection between
// this class and its layout
// XML file
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Locks
// the
// app
// into
// portrait
// orientation
getActionBar().setDisplayHomeAsUpEnabled(true); // Provides a "Back"
// navigation in the
// action bar of the app
// New Objects
tempDisplay = (TextView) findViewById(R.id.tempValue); // Creates a new
// TextView that
60. K
// displays the
// temperature
fOnOffButton = (ToggleButton) findViewById(R.id.fanOnOffButton); //
Creates
// a
// new
// ToggleButton
// called
// "Fan Control"
lOnOffButton = (ToggleButton) findViewById(R.id.lampOnOffButton); //
Creates
// a
// new
// ToggleButton
// called
// "Lamp Control"
rOnOffButton = (ToggleButton) findViewById(R.id.receptacleOnOffButton);
// Creates
// a
// new
// ToggleButton
// called
// "Receptacle Control"
// Handler object that processes incoming messages from the Arduino
h = new Handler() {
// Message handling method within an object. It receives as an
// argument message received by Android from the Arduino over
// Bluetooth.
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // If message is received
61. L
byte[] readBuf = (byte[]) msg.obj; // Store it in
array of
// bytes
String strIncom = new String(readBuf, 0, msg.arg1);
// Create
// string
// from
// bytes
// array
sb.append(strIncom); // Append string to
StringBuilder
int endOfLineIndex = sb.indexOf("rn"); //
Determine the
// end-of-line
if (endOfLineIndex > 0) { // If end-of-line,
String sbprint = sb.substring(0,
endOfLineIndex); // Extract
// string
sb.delete(0, endOfLineIndex + 2); // and
clear
tempDisplay
.setText(sbprint + "" + (char)
0x00B0 + " F"); // Update
// TextView
// Enable all ToggleButtons
fOnOffButton.setEnabled(true);
lOnOffButton.setEnabled(true);
rOnOffButton.setEnabled(true);
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // Get Bluetooth
// adapter
checkBTState(); // Call method that checks if Bluetooth is available and
// enabled
// "Fan Control" ToggleButton
fOnOffButton
.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
62. M
public void onCheckedChanged(CompoundButton
buttonView,
boolean isChecked) {
if (isChecked) { // If ToggleButton is "On",
mConnectedThread.write("y"); // send
character 'y'
// over Bluetooth to
// Arduino (y=>yes)
} else { // If ToggleButton is "Off",
mConnectedThread.write("n"); // send
character 'n'
// over Bluetooth to
// Arduino (n=>no)
}
}
});
// "Lamp Control" ToggleButton
lOnOffButton
.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton
buttonView,
boolean isChecked) {
if (isChecked) { // If ToggleButton is "On",
mConnectedThread.write("l"); // send
character 'l'
// over Bluetooth to
// Arduino
// (l=>light)
} else { // If ToggleButton is "Off",
mConnectedThread.write("d"); // send
character 'd'
// over Bluetooth to
// Arduino (d=>dark)
}
}
});
// "Receptacle Control" ToggleButton
rOnOffButton
.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton
buttonView,
63. N
boolean isChecked) {
if (isChecked) { // If ToggleButton is "On",
mConnectedThread.write("r"); // send
character r'
// over Bluetooth to
// Arduino
// (r=>receptacle)
} else { // If ToggleButton is "Off",
mConnectedThread.write("x"); // send
character 'x'
// over Bluetooth to
// Arduino (x=>no r)
}
}
});
}
// Two things are needed to make a connection, the MAC address and the UUID.
// Both are referenced in the next two methods.
// This method creates the Bluetooth connection.
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if (Build.VERSION.SDK_INT >= 10) { // If Android version is above 10
try {
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",
e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID); // The
// Bluetooth
// shield is
// the
// device
// returned
// to the
// caller
64. O
}
// This method is called when the app is started from the beginning or
// refreshed from being paused.
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
BluetoothDevice device = btAdapter.getRemoteDevice(address); // Set up a
// pointer
// to
// the
// remote
// node
// using
// its
// address
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed:
"
+ e.getMessage() + ".");
}
btAdapter.cancelDiscovery(); // Since discovery is resource consuming,
// ensure it is not
discovering while a
// connection is
// attempted or message is being sent.
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error",
"In onResume() and unable to close socket
during connection failure"
65. P
+ e2.getMessage() + ".");
}
}
// Create a data stream for server communication
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close
socket."
+ e2.getMessage() + ".");
}
}
// This method checks to see if the host phone has Bluetooth, and if so, if
// it is turned on.
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned
// on
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
// This method takes error messages from other methods and displays them as
// Android toasts.
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
// ConnectedThread class which extends the Thread class
private class ConnectedThread extends Thread {
66. Q
private final InputStream mmInStream;
private final OutputStream mmOutStream;
// This method instantiates input and output streams.
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
// This method processes incoming and outgoing byte arrays.
public void run() {
int bytes; // Bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
byte[] buffer = new byte[256]; // Buffer store for
the
// stream
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of
bytes and
// message in "buffer"
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer)
.sendToTarget(); // Send to message
queue Handler
} catch (IOException e) {
break;
}
}
}
// This method is called from the main activity to send data to the
// remote device.
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
67. R
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() +
"...");
}
}
}
// This method creates a menu to which application options can be added.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure.
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
“AutoActivity.java”
/*
* Course: CPET491 - Senior Design Phase II
* Title: Mobile Climate Control (MobileCC)
* Members: Michael McNair and Nathan Schaefer
* Date: 12/13/13
* File: AutoActivity.java
* Description: This class is the app's automatic control
* class. It contains a TextView, an EditText
* field, a ToggleButton, a Button, and a message
* handler. The TextView displays the indoor
* temperature value received and manipulated by
* the handler from the sensor connected to the
* Arduino. The EditText field designed to allow
* the user to enter a temperature value and the
* Button is supposed to send that temperature to
* the Arduino. The ToggleButton controls
* the lamp's action under automatic control.
* The message handler receives the incoming
* characters, appends them, and displays their
* value in the TextView. Within this class, a
* Bluetooth connection is created, which
* includes initiating a BluetoothAdapter and
* BluetoothSocket.
*/
// Program package
package com.example.mobilecc;
68. S
// Imports
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
// AutoActivity class which extends the Activity class
public class AutoActivity extends Activity {
// Declarations
private TextView tempDisplay; // This TextView is associated with the
// displayed temperature
private EditText enterTemp; // This EditText field is associated with the
// user's temperature input
private Button goButton; // This Button sends the user's temperature value
// to the Arduino
private ToggleButton automaticOnOffButton; // This ToggleButton is
//
associated with auto mode
//
control
private Handler h; // This handler is associated with receiving incoming
// characters
private BluetoothAdapter btAdapter = null; // Represents the host phone's
//
physical Bluetooth adapter
private BluetoothSocket btSocket = null; // Initiates and controls the
//
Bluetooth connection
private static final String TAG = "Bluetooth"; // Final string called
69. T
// "Bluetooth"
final int RECEIVE_MESSAGE = 1; // Status for Handler
private ConnectedThread mConnectedThread; // An object of the
//
"ConnectedThread" class that
//
manages input and output of
//
data
private StringBuilder sb = new StringBuilder(); // A dynamic sequence of
// characters used for
// assembling the
// temperature value
// Serial Port Profile (SPP) Universally Unique Identifier (UUID) service
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"); // This is
the
// unique ID
// of the
// Bluetooth
// shield
// MAC address of Bluetooth module
private static String address = "00:13:EF:00:07:87"; // SeeedStudio
// Bluetooth shield
// MAC address
/** Called when the activity is first created. */
@SuppressLint("HandlerLeak")
// The main method of the class. It is responsible for creating an instance
// of the "ManualActivity" activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto);// Creates connection between
//
this class and its layout
// XML
file
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Locks
// the
70. U
// app
// into
// portrait
// orientation
getActionBar().setDisplayHomeAsUpEnabled(true); // Provides a "Back"
// navigation in the
// action bar of the app
// New Objects
tempDisplay = (TextView) findViewById(R.id.tempValue); // Creates a new
// TextView that
// displays the
// temperature
enterTemp = (EditText) findViewById(R.id.enterThreshold); // Creates a
// new
// EditText
// field for
// user
// input
goButton = (Button) findViewById(R.id.enterButton); // Creates a new
// Button to send
// user temperature
automaticOnOffButton = (ToggleButton)
findViewById(R.id.autoOnOffButton); // Creates
// a
// new
// ToggleButton
// to
// turn
// lamp
71. V
// off
// automatically
// Handler object that processes incoming messages from the Arduino
h = new Handler() {
// Message handling method within an object. It receives as an
// argument message received by Android from the Arduino over
// Bluetooth.
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // If message is received
byte[] readBuf = (byte[]) msg.obj; // Store it in
array of
// bytes
String strIncom = new String(readBuf, 0, msg.arg1);
// Create
// string
// from
// bytes
// array
sb.append(strIncom); // Append string to
StringBuilder
int endOfLineIndex = sb.indexOf("rn"); //
Determine the
// end-of-line
if (endOfLineIndex > 0) { // If end-of-line,
String sbprint = sb.substring(0,
endOfLineIndex); // Extract
// string
sb.delete(0, endOfLineIndex + 2); // and
clear
tempDisplay
.setText(sbprint + "" + (char)
0x00B0 + " F"); // Update
// TextView
// Enable EditText, Button, and ToggleButton
enterTemp.setEnabled(true);
goButton.setEnabled(true);
automaticOnOffButton.setEnabled(true);
}
break;
}
72. W
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // Get Bluetooth
// adapter
checkBTState(); // Call method that checks if Bluetooth is available and
// enabled
// "Automatic Control" ToggleButton
automaticOnOffButton
.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton
buttonView,
boolean isChecked) {
if (isChecked) { // If ToggleButton is "On",
mConnectedThread.write("a"); // send
character 'a'
// over Bluetooth to
// Arduino (a=>auto)
} else { // If ToggleButton is "Off",
mConnectedThread.write("o"); // send
character 'o'
// over Bluetooth to
// Arduino (o=>off)
}
}
});
// "Enter" Button
goButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mConnectedThread.write(enterTemp.getText().toString()); //
When
// pressed,
// send
// the
// user's
// temperture
// value
// over
73. X
// Bluetooth
// to
// Arduino
}
});
}
// Two things are needed to make a connection, the MAC address and the UUID.
// Both are referenced in the next two methods.
// This method creates the Bluetooth connection.
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if (Build.VERSION.SDK_INT >= 10) { // If Android version is above 10
try {
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",
e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID); // The
// Bluetooth
// shield is
// the
// device
// returned
// to the
// caller
}
// This method is called when the app is started from the beginning or
// refreshed from being paused.
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
BluetoothDevice device = btAdapter.getRemoteDevice(address); // Set up a
74. Y
// pointer
// to
// the
// remote
// node
// using
// its
// address
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed:
"
+ e.getMessage() + ".");
}
btAdapter.cancelDiscovery(); // Since discovery is resource consuming,
// ensure it is not
discovering while a
// connection is
// attempted or message is being sent.
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error",
"In onResume() and unable to close socket
during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream for server communication
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
@Override
75. Z
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close
socket."
+ e2.getMessage() + ".");
}
}
// This method checks to see if the host phone has Bluetooth, and if so, if
// it is turned on.
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned
// on
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
// This method takes error messages from other methods and displays them as
// Android toasts.
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
// ConnectedThread class which extends the Thread class
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
// This method instantiates input and output streams.
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
76. AA
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
// This method processes incoming and outgoing byte arrays.
public void run() {
int bytes; // Bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
byte[] buffer = new byte[256]; // Buffer store for
the
// stream
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of
bytes and
// message in "buffer"
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer)
.sendToTarget(); // Send to message
queue Handler
} catch (IOException e) {
break;
}
}
}
// This method is called from the main activity to send data to the
// remote device.
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() +
"...");
}
}
}
// This method creates a menu to which application options can be added.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
77. BB
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure.
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android Layouts (XML Files)
“activity_main.xml”
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainMenu" >
<Button
android:id="@+id/autoButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/manualButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="@string/auto" />
<Button
android:id="@+id/manualButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/autoButton"
android:layout_alignParentTop="true"
android:layout_marginTop="129dp"
android:text="@string/manual" />
</RelativeLayout>
“activity_manual.xml”
<?xml version="1.0" encoding="UTF-8"?>