Home IoT & Hardware Arduino Android Blueprints

Arduino Android Blueprints

books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Publication date:
December 2014
Publisher
Packt
Pages
250
ISBN
9781784390389

 

Chapter 1. Setting Up Your Workspace

The first chapter of this book will teach you the basics of the Arduino and Android development so that you can be sure you have the basics required for the more advanced tutorials you will find in the rest of this book.

On the Arduino side, we will build a very simple project with a relay module (which is basically a switch that can be controlled with Arduino) and a temperature and humidity sensor. We will also see the basics of the Arduino IDE and the basic commands of the aREST library, which is a framework to easily control Arduino boards. We will use this library in several chapters of this book to make it really easy to control the Arduino board from an Android device. In this first chapter, we will simply try out the commands of the aREST library by having the Arduino board connected to your computer via a USB.

From the Android development point of view, we will work together to set up a development environment and ensure that your computer and the Android device are ready for development purposes. We will start off with a simple Android app that displays the legendary text, Hello World.

Android Studio is an IntelliJ-based Integrated Development Environment (IDE) fully supported by the Android development team, which will provide you with the necessary tools and resources to make sure that you develop a functional and aesthetic Android app.

Android Studio is in beta but the software is updated on a frequent and regular basis by a dedicated team at Google, which makes it the natural choice to develop our Android projects.

 

Hardware and software requirements


The first thing you will need is an Arduino Uno board. We will use this board throughout this book to connect sensors, actuators, and wireless modules and make them interact with Android. Then, we will need a relay module. A relay is basically an electrical switch that we can command from Arduino, which can allow us to control devices such as lamps. This project uses a 5V relay module from Polulu, which properly integrates a relay on a board, along with all the required components to control the relay from Arduino. The following is the image of the relay module that was used in this chapter:

You will also need a DHT11 (or DHT22) sensor, along with a 4.7K resistor, for temperature and humidity measurements. A resistor is basically a device to limit the current flowing into an electrical device. Here, it is necessary to ensure the correct functioning of the DHT sensor.

Finally, you will need a small breadboard and jumper wires to make the different hardware connections.

The following is the list of all hardware parts you will need for this project, along with links to find these parts on the Web:

On the software side, you will need the Arduino IDE that we will also use in the rest of this book. You can get it at http://arduino.cc/en/Main/Software.

The installation process of the IDE is very simple; you simply have to open the file and follow the onscreen instructions.

You will need the library for the DHT11 sensor, which can be found at https://github.com/adafruit/DHT-sensor-library.

You will also need the aREST library found at https://github.com/marcoschwartz/aREST.

To install a given library, simply extract the folder in your Arduino/libraries folder (or create this folder if it doesn't exist yet). Your Arduino folder is where all the sketches are stored, and you can define this folder in the preferences of the Arduino IDE.

Preparing for Android development requires that we get ready to design and develop the app, and the following checklist will guide you with having the basics ready for any project:

  • Java Developer Kit Version 6 (or higher)

  • Android Studio

  • Android Software Development Kit

  • Android Device with Bluetooth SMART technology

We will also work together to make sure that you have everything properly set up.

 

Installing Java Developer Kit


Android Studio will not work without Java Developer Kit (JDK); therefore, it's necessary to know what Java version you have installed (in this particular case, the Java Runtime Environment will not be enough).

Checking the JDK version

It is mandatory that you check the version of your JDK for compatibility purposes.

Mac

Open Terminal and type the following command:

java –version

This is what will be shown on the screen:

Windows

Open Command Prompt and type the following command:

java -version

This is what will be shown on the screen:

Installing Java

If you do not have Java installed, or if your version is below 6.0, install the Java JDK by clicking on the following customized and shortened link and choosing the version that applies for you:

http://j.mp/javadevkit-download

The following window will open:

The main recommendation for these projects is that you install a version of JDK 6.0 or higher.

Select the JDK for your operating system. On an Intel-based Mac, you can follow this useful table to see whether your Mac is 32-bit or 64-bit:

Processor Name

32- or 64-bit processor

Intel Core Solo

32 bit

Intel Core Duo

32 bit

Intel Core 2 Duo

64 bit

Intel Quad-Core Xeon

64 bit

Dual-Core Intel Xeon

64 bit

Quad-Core Intel Xeon

64 bit

Core i3

64 bit

Core i5

64 bit

Core i7

64 bit

You can check for Processor Name by clicking on the Apple logo in the top-left corner of your screen followed by About my Mac.

In the case of Windows, to see whether your computer is running a 32-bit or 64-bit version of Windows, you need to do the following:

  1. Click on the Start button.

  2. Right-click on My Computer, and then click on Properties. If x64 edition is listed under system, your processor is capable of running 64-bit-enabled applications.

 

Installing Android Studio


Let's see how we install Android Studio on Mac and Windows:

  1. Go to the Android Developers site at http://developer.android.com. The following screen will appear:

  2. Click on Android Studio; you will be directed to the landing page where your operating system version will be detected automatically, as shown in the following screenshot:

  3. Accept the Terms and Conditions of the software use agreement:

Mac

Double-click on the downloaded file, follow the prompts, and then drag the Android Studio icon into your Applications folder:

Windows

Open the downloaded file, and then go through the following Android Studio Setup Wizard window to complete the installation process:

 

Setting up the Android Software Development Kit


The process of setting up the Android Software Development Kit (SDK) has improved vastly with the introduction of Android Studio, as the latest SDKs come preinstalled with the Android Studio install package. In order to develop the projects detailed in the following chapters, it would be very helpful to understand how you can install (or even uninstall) SDKs within Android Studio.

There are a number of ways to access the SDK Manager. The most straightforward way is through the following Android Studio main toolbar:

Another option would be via the Launch menu where you will be faced with the following options:

In order to access the SDK Manager, you will need to click on Configure, where the following screen will appear, and then click on SDK Manager:

The previous screenshot shows us what the SDK Manager looks like. If you need to install any packages, you need to check the mark of that particular package, click on Install packages, and then finally accept the licenses, as shown in the following screenshot:

Setting up your physical Android device for development

The following are the three main steps that need to be executed in order to enable your Android device for development:

  1. Enable Developer options on your specific Android device.

  2. Enable USB debugging.

  3. Entrust the computer with an installed IDE via secure USB debugging (devices with Android 4.4.2).

Enabling Developer options

Depending on your device, this option might vary slightly, but from Android 4.2 and higher, the Developer options screen is hidden by default.

To make it available, go to Settings | About phone and tap on Build number seven times. You will find Developer options enabled by returning to the previous screen.

Enabling USB debugging

USB debugging enables the IDE to communicate with the device via the USB port. This can be activated after enabling Developer options and is done by checking the USB debugging option by navigating to Settings | Developer options | Debugging | USB debugging.

Entrusting the computer with the installed IDE using secure USB debugging (devices with Android 4.4.2)

You have to accept the RSA key on your phone or tablet before anything can flow between the device via Android Debug Bridge (ADB). This is done by connecting the device to the computer via a USB, which triggers a notification entitled Enable USB Debugging.

Check Always allow from this Computer followed by clicking on OK.

 

Hardware configuration


For the first project of this book, there are only a few hardware connections to make. We simply need to connect the relay module and the DHT11 sensor to the Arduino board.

The following image summarizes the hardware connections for this chapter (with the DHT sensor on the left of the breadboard, and the relay module on the right):

The first thing you need to do is to connect the power from the Arduino board to the power rails on the side of the breadboard. Connect the Arduino 5V pin to the red power rail on the breadboard, and the Arduino GND pin to the blue power rail on the breadboard.

For the DHT11 sensor, you first need to have a look at the pins configuration of the sensor by visiting http://www.rlocman.ru/i/Image/2012/09/06/DHT11_Pins.jpg.

You need to first connect the power supply; the VCC pin goes to the red power rail on the breadboard, and the GND pin goes to the blue power rail. You also need to connect the DATA pin to pin number 7 of the Arduino board. Finally, place the 4.7K Ohm resistor between the VCC and the DATA pin of the sensor.

For the relay module, you have three pins to connect: VCC, GND, and SIG. Connect the VCC pin to the red power rail on the breadboard, GND to the blue power rail, and finally, connect the SIG pin to Arduino pin 8.

The following is an image of the completely assembled project:

 

Learning to use the aREST library


Now that our hardware is assembled, we are going to see the basics of the Arduino environment, and how to use the aREST library that we are going to use in several chapters of this book to control Arduino from an Android phone.

The aREST library will allow us to simply control the Arduino board externally using the same commands, whether it is using an USB cable, Bluetooth, or Wi-Fi. Without this library, we will have to rewrite the same code several times for all the chapters of the book. To find a complete documentation on the aREST library, you can visit https://github.com/marcoschwartz/aREST.

The main window of the Arduino IDE is where you enter the code to program the Arduino board.

Arduino code files are usually called sketches. The following screenshot is of the Arduino IDE with the code of this chapter already loaded:

You will basically use two buttons that you can find on the left-hand side of the toolbar. The first one, with the check sign, can be use to compile the code. The second one will be used to upload the code to the Arduino board. Note that if the code has not been compiled yet, the upload button will also compile the code before uploading.

The second important window of the Arduino IDE is called the serial monitor. This is where you can monitor what your Arduino project is doing, using the Serial.print() statements in the code to generate debug output. You can access it by clicking on the top-right icon of the Arduino IDE main window.

The following screenshot shows what the serial monitor looks like:

We are now going to build our first Arduino sketch in this book. What we want to achieve is simply to control the relay and read data from the DHT11 sensor. To do so, you are going to use the aREST library by sending commands from your computer. In the next chapter of this book, we are going to use the same commands but via a Bluetooth or Wi-Fi connection. The goal of this section is really to make you familiar with the commands of the aREST library.

The following code is the complete Arduino sketch for this part:

// Libraries
#include <aREST.h>
#include "DHT.h"

// DHT sensor
#define DHTPIN 7
#define DHTTYPE DHT11

// Create aREST instance
aREST rest = aREST();

// DHT instance
DHT dht(DHTPIN, DHTTYPE);

// Variables to be exposed to the API
int temperature;
int humidity;

void setup(void) {
  // Start Serial (with 115200 as the baud rate)
  Serial.begin(115200);
  
  // Expose variables to REST API
  rest.variable("temperature",&temperature);
  rest.variable("humidity",&humidity);
  
  // Give name and ID to device
  rest.set_id("001");
  rest.set_name("arduino_project");
  
  // Start temperature sensor
  dht.begin();
  
}

void loop() {  
  
  // Measure from DHT
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  
  temperature = (int)t;
  humidity = (int)h;
  
  // Handle REST calls
  rest.handle(Serial);
  
}

Let's explore the details of this Arduino sketch using the following steps:

  1. The Arduino sketch starts by importing the required libraries for the project:

    #include <aREST.h>
    #include "DHT.h"
  2. After that, we need to define on which pin the DHT11 sensor is connected to, and which is the type of the sensor:

    #define DHTPIN 7
    #define DHTTYPE DHT11
  3. We also need to create an instance of the aREST library:

    aREST rest = aREST();
  4. We also need to create an instance of the DHT11 sensor so that we can measure data from it:

    DHT dht(DHTPIN, DHTTYPE);
  5. Finally, we need to create two variables that will contain our measurements:

    int temperature;
    int humidity;
  6. In the setup() function of the sketch, we need to start the serial port:

    Serial.begin(115200);
  7. Next, we need to expose our two measurement variables so that we can access them via the serial port using the aREST library. Note that we have to pass the reference to these variables, not their values, as shown in the following code:

    rest.variable("temperature",&temperature);
    rest.variable("humidity",&humidity);
  8. We also set an ID and name to our project. This will not play any role here, but is simply to identify our board in case we have many of them:

    rest.set_id("001");
    rest.set_name("arduino_project");
  9. Finally, we start the DHT11 sensor:

    dht.begin();
  10. Now, in the loop() function of the sketch, we make the measurements from the DHT11 sensor, and convert these measurements to integers (which is called "casting" in C):

    float h = dht.readHumidity();
    float t = dht.readTemperature();
    
    temperature = (int)t;
    humidity = (int)h;
  11. Note that here we are converting these numbers into integers because it is the only variable type supported by the aREST library. However, as the resolution of the DHT11 sensor is limited, we are not losing any information here. Finally, we handle any requests coming from the outside using the following code:

    rest.handle(Serial);

    Note

    Note that all the code for this chapter can be found in the GitHub repository of the book at the following link:

    https://github.com/marcoschwartz/arduino-android-blueprints

It's now time to upload the sketch to your Arduino board. If you have any error when compiling, make sure that you installed all the required Arduino libraries for this chapter.

When this is done, simply open the serial monitor (making sure the serial speed is set to 115200). Note that you could do the same with your own serial terminal software, for example, CoolTerm found at http://freeware.the-meiers.org/.

Now, we are going to test that the aREST library is working correctly. Let's proceed with the following steps:

  1. First, we are going to query the board for its ID and name. To do so, type the following:

    /id
    
  2. You should be greeted by the following answer:

    {"id": "001", "name": "arduino_project", "connected": true}
    
  3. We are now going to see how to control the relay, as this is something we are going to do several times in this book. First, we need to define that the relay pin, which is pin number 8 of the Arduino board, is an output. To do so, we can simply type:

    /mode/8/o
    
  4. You should receive the following answer on the serial monitor:

    {"message": "Pin D8 set to output", "id": "001", "name": "arduino_project", "connected": true}
    
  5. Now, to activate the relay, we need to set the pin 8 to a HIGH state. This is done the following command:

    /digital/8/1
    
  6. You should instantly receive a confirmation message, and hear the relay click. To switch the relay off again, simply type the following code:

    /digital/8/0
    
  7. Now, we are going to read data from the board using the aREST library. For example, to read the temperature variable, you can simply type the following code:

    /temperature
    
  8. You will receive the following confirmation message with the value of the temperature:

    {"temperature": 28, "id": "001", "name": "arduino_project", "connected": true}
    
  9. You can do the same for humidity:

    /humidity
    
  10. You will receive a similar message back:

    {"humidity": 35, "id": "001", "name": "arduino_project", "connected": true}
    

If this is working, congratulations! You now know the basics of the aREST library that we will use throughout the book. Note that for now we are using these commands via serial communications, but later in the book, we will first use the same commands via Bluetooth, and then via Wi-Fi to command the Arduino board from an Android device.

Now that we have seen how the aREST library is working, we are going to create our first Android project. Note that in this introductory chapter, we won't connect both together; this will be done in the next chapter of the book.

 

Creating your first Android project


In order to get started in the world of Android application projects, it would be very useful to set up a very basic project that goes through the two main processes in Android application development: coding the application and then testing it on an Android physical device.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Setting up your first Hello Arduino project

Click on New Project when Android Studio launches as shown in the following screenshot:

An important step within Android application development is configuring your project. This project will be using Android 4.3 as the minimum target SDK, since we intend to use the Bluetooth Low Energy API, which was introduced in this particular version of Android. In this case, we will name the project Hello Arduino and write down your company domain, as the convention for application package names is the reverse of your chosen domain.

Refer to the following screenshot:

For the purposes of this particular project, we will go ahead and choose the most basic project, Blank Activity, as shown in the following screenshot. The other choices provide added functionality that we do not need at this stage.

In the following screenshot, we choose Blank Activity, and we need to give a name to our main Java file. Let's keep it as MyActivity:

Once you follow through all the previous steps, you will be welcomed to this workspace, which gives a good overview of the project tree, main code editor, and the device that shows a preview of the User Interface (UI), as shown in the following screenshot:

In this particular project, there will be no need to modify the existing code and therefore we will proceed with building our app and launching it on our physical Android device.

Installing your app on your physical device

Previously, we have connected and enabled our physical Android device via a USB. Within Android Studio, we need to set up the configuration to run our Android application.

This is done by choosing Editing Configurations from the main toolbar as shown in the following screenshot:

In the Editing Configurations window, we will click on the + sign and choose Android Application where we set up the configuration with the following settings and confirm them by pressing OK:

After setting up everything, we are ready to run the app. Choose the App configuration, which we previously set up, and press the Play button (green triangle) as shown in the following screenshot:

There is the possibility of creating an Android Virtual Device (AVD) to install the application. However, at this point in time, there are no virtual emulators that support Bluetooth, which we will need for a number of projects in this book. So, we will focus on setting up your Android physical device running Android 4.3 or higher.

In the next step, choose your physical device and press OK, as shown in the following screenshot:

You should expect the following to show up on your Android device if you have set up everything in the correct manner:

 

Summary


Let's summarize what we did in this chapter of the book. We built a very simple Arduino project comprising an Arduino board, a relay module, and a temperature and humidity sensor. We saw how to connect these components together so that we can control the relay as an output and read data from the sensor. We also saw the basics of the aREST library, which we will use in the whole book to control the Arduino board from an Android device.

On the Android side, we have prepared our IDE and Android device for development, which will prepare us for the upcoming projects that we have prepared for you in this book and help us have a seamless experience. We also had the opportunity to compile our first app and get it up and running on our Android device.

At this stage, you can already repeat the steps we took in this chapter to really get familiar with the Arduino IDE, the commands of the aREST library, and the Android development environment. We will use these tools extensively in the rest of this book; so, it is crucial that are you familiar with them.

Latest Reviews (2 reviews total)
The book gives enough detailed information that a reasonably-experienced electronics enthusiast should have no trouble completing any of the projects. It covers both the hardware and software components of the build. On the other hand, it is probably not the best book for somebody new to Arduino, as the projects are often a little complex for a complete beginner. If you are interested in building one of the 8 or so projects in the book, or are skilled enough to modify one of the projects to suit your needs, the book would be very useful. Because it doesn't go into a lot of detail on the Android software side, mostly just providing code to use without a detailed dissection of how the code works or how to modify it, you would probably need a fairly extensive knowledge of Android programming if you intended to make major changes to the software code of the projects. Projects include: Bluetooth Weather Station, Wi-Fi Smart Power Plug, Wi-Fi Remote Security Camera, Android Phone Sensor, Voice-activated Arduino, Control an Arduino Board via NFC, Bluetooth Low Energy Mobile Robot, and Pulse Rate Sensor.
Have not yet reviewed this title.
Arduino Android Blueprints
Unlock this book and the full library FREE for 7 days
Start now