Introduction
The challenge of creating a product that isn't only software based is that you end up having to work with a number of technologies. However that can also be the most interesting part.
Here's a crude drawing of a complete overview of the project. It shows all of the components required and should give you an idea of the basics of how this project works.
If you read and work through this entire article you will have a working device which will allow you (and anyone else you provide with the Android app) to open your garage door via Bluetooth.
Fritzing Circuit
If you know about the great app from fritzing.org then you know you can draw and test your circuit. I've added the schematic for the completed board up there at: http://fritzing.org/projects/bluetooth-garage-door-opener[^]
At the site you can get the circuit document and alter it for your needs and test it.
The final schematic shows how simple the electronics really are to build and how few components you really need:
List of Required Parts
I've provided a list of all the parts with the places where I recommend you get them throughout the article and then at the end of this article I've listed them all together for your easy reference.
It Opens My Garage Every Day
Here's what the final product will look like -- it's still the raw circuit on a breadboard but it works very well. I depend upon it opening my overhead garage door every day.
Video Demonstration Of It In Use
Here's a youtube video where you can see it work. It's not a great video but it gives you the idea and you can see the relay activate when I press the button on the Android app.
Never Buy A Garage Door Remote Again: Open Your Door With Your Android Phone (via Bluetooth) - YouTube[^]
Unfortunately, my video shows me opening the garage door from inside. Well, that may make you think Bluetooth won't work at a very far range.
Bluetooth Range: Does It Work From a Reasonable Distance?
I was extremely impressed with my initial test of the Bluetooth in my cheap phone and the inexpensive Bluetooth module. It works with no problem through the brick of my garage and the metal of my garage door and from at least 20 feet outside of the garage. It's really quite fantastic.
I Aim to Teach You Quite A Lot In This Article
In this article we will
- examine some fundamental electricity / electronics concepts.
- learn to wire up a simple circuit which uses a Bluetooth module (HC-05), an AVR atmega328 and a relay module (easy-to-use electronic switch)
- see how to repurpose old device chargers to power the circuit
- learn to write some basic AVR-C (C programming language used by Atmel AVR chips).
- discover how to hook up a chip programmer (hardware) to flash your programs into the memory of your ATMega chip
- use AVRDude (software) and GNU toochain to compile and program our Atmel chip
- Examine the code to create an Android app which will allow user to send data via Bluetooth to another device
- Walk through the discovery / design process as I attempted to break the problem down and create a solution.
- Provide links to the exact hardware items I used in the project so you can get an idea of availability and cost.
I think this is a great first project for learning how to bind together hardware and software knowledge because when you complete the article you'll have a device which can save you money*.
*Normally, the more people you need to be able to open your garage door then the more remotes you have to purchase. However, with the Bluetooth solution new users can be added by simply installing the Anroid app and having the user pair her device. No additional hardware or cost required.++
++ You may think this is a security issue since it sounds as if anyone could pair their device to your garage door and open it, however, you have to press a physical button on the device to initially pair a new device and then that person has to type in a 4 digit security code.
Background
I recently moved and discovered my new home has a very old overhead garage door opener. However, there were no wireless remotes provided to us from the previous owner. Normally you could buy a universal wireless remote but these are so old that you have to buy the original LiftMaster remotes to pair up with them. Those remotes are difficult to find and more expensive (of course) than the universal ones. Each one was around $30USD (they may be less now).
It all annoyed me since the entire idea of being forced to buy a seperate remote at $20USD each time is ridiculous. We all carry around devices (phones, pads, etc) that are far more powerful and should have all the technology needed to control a simple garage door.
There Must Be a Way
I'm no hardware guru but I have been developing software since 1995 or so. But I figured there just has to be a better way to control my garage door. At first the idea of the wireless garage door control might seem somewhat dfficult to reverse engineer. I mean wouldn't that mean I need to know all about R/F (radio frequency) and all that blather. No.
All I really need to know how to do is activate a switch remotely.
Activate A Switch Remotely
All a garage door opener really is is a switch on the wall, right? I know the switch goes up to the motor installed on the ceiliing and that when I push the switch the motor activates. So all I need to know how to do is replace the switch or activate it remotely. Of course, an additional constraint is that I want my wall switch to continue to working as it does also.
First Thing I Did Was Examine My Problem
The first thing I did was walk down to my garage and look at the switch on the wall. It's old and extremely ugly.
I've highlighted the incoming wires (from the Garage Door Motor -- top) and the momentary switch which a user presses to open or close the garage door (bottom).
You just push that flat panel down and the overhead motor activates. Well, I understand that this is just an open (unconnected) switch and when I push it I am connecting the terminals together and completing the circuit.
That's simple enough.
So I then figured I should just take the switch off the wall and see how it worked. If I could add a couple of wires (one at each side of the terminal) and connect them together to complete the circuit then I figured I'd have a start.
What About Electrocuting Myself or Others To Death?
That's definitely a concern. Disclaimer: I am not a licensed electrician. Please do not take apart your switches and accidentally electrocute yourself.
Clue That Garage Switch Is Relatively Safe
There is a clue that I took that indicated to me that messing around with the garage door switch is probably safe. The gauge of wire that is included in a circuit can indicate how much voltage and current it carries. This is a rule of thumb and not electrical advice of any kind. Again, please don't do things that you're unsure about. I don't want you to hurt yourself.
However, most of us who are familiar with garage door openers know that there are generally two wires coming down to the switch from the motor up on the ceiling. You may have noticed that those wires are very small (thin).
That probably indicates that they do not carry much current and/or voltage. And, if you search the internet for "momentary switch garage door" you'll see that most of the time those wires only carry about 12v (volts).
I found a schematic showing this at DIY: Integrate a 3V (3 volt) garage door opener remote to your vehicle (newbie frien - Toyota FJ Cruiser Forum[^]
First Step - Add Two Wires
My first step was to add two wires so that I could extend the circuit to my new remotely controlled switch. My first step looked like the following as I took the switch off the wall and looked in behind it.
You can see the incoming wires (from Garage Door Motor) and then I added two wires to those same screws by simply loosening them up and curling the wires around them and then tightening the screws back down.
After I had added them and put the panel back on the wall, it looked like the following:
I could then touch those two wires together and the garage door motor (GDM from here on out) would be activated. Or, if the GDM was already activated then touching the two wires together de-activated it.
This seems like a very simple step and I guess it is, but it was also an important one because I knew it meant that if I could somehow remotely control the connection of these two wires (complete the circuit) then I would have what I wanted. What I needed was some kind of electroncially activated switch.
Electronically Activated Switch
Somewhere deep inside my mind was a bit of information I had read in the fantastically well-written book by Programming Author Legend, Charles Petzold Code: The Hidden Language of Computer Hardware and Software, eBook - Amazon.com[^]
Electronic Relay
Among many other interesting things, Petzold explains how that relays are basically switches controlled by electromagnets. Sweet! That's what I need.
How Do Relays Work?
The basics of the most simple relay is something like this:
- when an voltage is applied to the main relay circuit, an electro-magnet is activated
- when the elecro-magnet is activated it pulls a metal lever (switch) from its normally open (disconnected) position to the closed position.
- When the lever moves to the closed position the secondary circuit is completed and electricity can flow in that circuit (this would be the activation for our GDM).
ElectroMagnet : Coil around Iron Core
An electromagnet can be created quite easily by wrapping a piece of iron in copper wire to create a coil. When electricity is sent through the copper wire then electromagnetic field is generated. That's basically how relays are created. The most simple ones are composed of a coil and a piece of metal which rests in one position and moves to the closed position when the voltage is applied to the coil and the magnetic field moves the metal switch.
Please remember my explanations are those of a layman so those of you with degrees in Electronics Engineering take it easy on me. :)
Here's a simple circuit drawing of a relay that is similar to what I'm talking about. SPST means single-pole single-throw. That just means there's a single switch that switches one way.
That drawing comes from (https://upload.wikimedia.org/wikipedia/commons/6/67/Relay_symbols.svg).
More Details To Relays: I Want An Easy One
There are many more details to creating an actual relay in a circuit. And even if you buy one of the modular types which is just the relay unit itself, you will have to add some diodes to insure the switch operates properly. That's why for this project I bought a complete pre-made relay circuit module. They include all the diodes to make it work properly. Plus they include everything you need to connect the primary and secondary circuits easily and are really cool and easy to use.
Relay Circuit Module : Inexpensive and Easy To Use
The one I use in ths project looks like :
I bought it through Amazon and you can get yours there too if you like ( Amazon.com: Tolako 5v Relay Module for Arduino (Works with Official Arduino Boards)[^])
The big blue box in the middle of the circuit board is the actual relay (the coil which generates the magnetic field and moves the switch).
Also, notice that this device is sold as being "for Arduino". That's because most people who program AVR ATMega chips are using Arduino boards. We aren't but it works fine. They could've marketed it as for AVR Chips and they would've been fine but Arduino has a huge buzz, of course.
Output Circuit
The first view shows you the output circuit. They are the three ports where our wires will go and each port has a screw which allows you to firmly connect the output wires with no need for solder. This is the circuit we will connect our GDM wires to. Take a look at the original picture where I added the two wires to my switch. Those two wires will go in two of these output ports. You can see that in the first picture of the completed project oo. This is the circuit which will ultimately be turned on when we want to activate our GDM.
Input Circuit
However, to use the relay module you have to provide an input circuit also. That's the circuit which will decide whether or not the GDM should be activated or not. More about this as we move on. You can see the 3 pins of the input circuit in the second view of the relay module above.
Why Are The Three Input Pins On Relay Module Instead of Two?
The way the relay module works is very simple. You place a positive volage of 5 to 12 volts on the + (positive) pin and a ground wire on the - (minus) pin. Then you hook up a wire to something else which will supply 5 to 12 volts also. That's the pin marked IPP (InPut Port maybe?) on this relay module. When 5v is applied to that pin then the coil will be activated the electromagnet will be on and the switch will turn on completing our circuit on the output side.
Why Are There Also Three Output Ports?
Okay, you got me. I did not tell the complete story about relays above because I was attempting to keep it simple. There are relays which actually have two output circuits on them. Our module actually has two output circuits. That's why we have three output ports.
Middle Port : Common
The middle one is common to both So you will always have one wire in the middle port and it is called the common.
Then each of the other ports (left and right) have their own name.
Normally Open
The NO (Normally Open) port is off when there is no voltage (or below 5v) applied to the IPP pin.
Normally Closed
The NC (Normally Closed) port is on when there is no voltage (or below 5v) applied to the IPP pin.
Then, when 5v is applied to the IPP pin the NO closes and the NC opens, since the switch flips.
This tiype of switch is called a SPDT (single pole, double throw) since it can throw two different ways.
The circuit looks like the following:
In the previous image, we consider the schematic to represent the non-powered version of the circuit. So you can see that the B to C circuit would be the NC (normally closed or unpowered on) circuit and the A to C circuit would be the NO (normally open or unpowered off) circuit.
So now we've got the main component that will help us solve this problem. Let's hook it up into a very simple circuit so you can see it work. We'll just make it so that when voltage is applied to the IPP then the switch will throw and an LED will be lit up on the output side.
First, I'll draw the simple circuit and then I'll show you a video of it working.
Relay Represents Three Distinct Circuits
There are really three distinct circuits to our relay module.
- There is the input circuit. This is the circuit that affects which output circuit is on.
- There is the NC - normally closed output circuit. This circuit is on when there is no voltage applied to the IPP. (You can see in the next crudely drawn image that there is no voltage applied to the IPP so the LED on the NC (output) circuit is on.
- Finally there is the NO - normally open output circuit.
Now, if we flipped the switch on the input circuit so it were closed, then the switch on the output circuit would flip and the NC circuit would become open and the LED would turn off and the NO circuit would be closed which would then turn on the LED at the top of the diagram.
Here's a quick video showing that actually happen. Just keep in mind that there is an input circuit and an output circuit and it'll make sense.
Video Of Relay In Action
Electronics - Using a Relay Module : Input and output circuits[^] (It's only 52 seconds.)
Did We Spend Too Much Time On The Relay?
Maybe you think we spent far too much time on this relay module. However, consider that this is a foundational component and once you understand how it works it opens up a world of control to you. You can use this in all manner of future projects.
Also, this is the crux of our project. We need a way to flip a switch electronically and now we can do that.
Control Just About Any Electrical Device
And once you learn how to control your garage door via Bluetooth, you will be able to use this same circuit to control just about any other electrical device imaginable.
What Component Will Decide When To Apply Voltage to the Relay?
However, you may wonder how something will decide when the voltage should be applied to the relay. As you saw in the video I am manually (using a wire I am holding) applying the 5v to the input pin.
Send A Signal To Activate
We know in our case we want to send some kind of signal to the relay that will tell it to activate so the switch will be flipped and the GDM will be started.
We could wire something up so that even if we were far away we could press a button and 5v would be applied to the wire and that wire would be connected to the IPP on the relay module and then it would activate the magnetic coil and the GDM would start.
But that is obviously a wired solution and we don't want that. It's not practical in this situation. That's basically what we have with our wall switch anways. Besides we know we want to receive a wireless signal that activates the GDM.
Ah, Bluetooth is a wireless signal. I often watch the Adafruit Industries, Unique & fun DIY electronics and kits[^] videos and keep up on neat components and I believe I've seen some inexpensive Bluetooth items so that will probably work.
Enter Bluetooth
I'm trying to keep this project as cheap and simple as possible. I start searching around and I find an extremely simple (though not fantastically documented) Bluetooth module which seems to be some kind of defacto standard which is built by multiple companies.
HC-05 Bluetooth Component (defacto standard)
Here's the one I ended up purchasing. You can get it at amazon for around $8.00USD :Amazon.com: HC-05 Wireless Bluetooth Serial Transceiver Module Slave And Master[^] Here you can see the front and back views.
Pins On Devices Provide Access to Functionality
The back view is nice because we learn a bit about the device and how it works. We can see the way to get the module to power up is to simply provide 3.6v to 6v on the pin marked VCC (voltage). and wiring up the GND (ground) pin to ground in order to create a complete circuit.
Bluetooth Module Is Easy To Use (Mostly)
That means if we took this module and plugged it into a breadboad added a power which provides 3.6v - 6v then it will start broadcasting a Bluetooth signal so other devices can connect.
The Real Question: How Do We Communicate With Bluetooth Device?
However, once the module is powered up and broadcasting and a device connects, what we want to know is how do we communicate with the Bluetooth device. How do we receive the messages from a device and power our relay so our GDM will be activated? We will see how to do this. But let's continue our basic investigation of what the pins on the Bluetooth provide. But first, let me make mention of the voltages on these various devices and why they are important for us to watch as we buy components.
A Note On Device Voltages
Notice that our relay module indicates that it works in a range of 5v - 12v and the Bluetooth module works in the range of 3.6v - 5v. This is important to know since we are going to want to attempt to power both items on the same circuit using one power supply of some type. When we start talking about the Atmel ATMega328 chip we will also learn that it has an operating voltage range of 1.8v - 5.5v.
Okay, now back to talking about our HC-05 Bluetooth module.
Let's hook it up, connect a device to it and see what we can do.
Powering Up Bluetooth Module And Pairing A Device
Here are the basic steps (from Google - Connect to Bluetooth - Nexus Help[^]) on how to pair a device. The default password for these HC-05 modules is : 1234
Sending and Receiving Data From the Bluetooth Module
Now that we've got it going and we have a device paired to it. How do we talk to it? How can we know that we are talking to it?
All the Bluetooth Module Really Does: Send & Receive Data
Getting the data the Bluetooth module receives is the challenging part. Basically the Bluetooth module just does two things:
- Receives data over wireless and writes it to its serial transmit pin (Tx). This data is written on that pin as a series of voltages, something like morse code.
- Then, when something writes data (a series of voltages are applied) to the Rx pin on the Bluetooth module it converts that data to a wireless signal and sends the data.
This all means that if you could somehow know when voltages are on the Tx pin then you could know that there is a message to read. And, if you wanted to send a message out of the Bluetooth you'd need to write voltages to the Rx pin.
All We Really Want Is the Data
The problem is that we cannot get the data that the Bluetooth module is receiving. You have to think about that for a moment. How could we read the voltages off of the Tx pin? Well, we could take the Tx pin and wire it directly to the relay's IPP (input port). But that would mean that every bit of data that came across the Tx pin of the Bluetooth module would end up pulsing the input port and activating the relay numerous times a second. In turn, that would cause our GDM to activate and de-activate numerous times a second. That won't work for us.
The Reason We Need a Processor
What we really need is something that can process the incoming data (data coming in on Bluetooth). We need a way to write a program that can examine the data and decide what should be done. Since we cannot write any programs for the Bluetooth module or process the data it sends and receives we need another component to do that work. That component is the main microprocessor of our project: the ATMega328PU.
Atmel ATMega Series of Chips
I could tell you all the history and specifications of these chips but instead let's focus on the chip as a product developer who is attempting to get a product finished as cheaply and quickly as possible. That's what is important to us. First of all, why are the ATMega chips on rise?
The AVR chips were first developed back in 1996 and were one of first chips and were...
Quote:
"..one of the first microcontroller families to use on-chip flash memory for program storage, as opposed to to one-time programmable ROM, EPROM, or EEPROM used by other microcontrollers at the time."
from Atmel AVR - Wikipedia, the free encyclopedia[^]
That technology meant these chips could have programs flashed into their memory far easier that previous chips.
Arduino Development Boards
This set the table for the developers who came along and produced the Arduino development boards which are open source hardware (anyone can build the Arudino board itself and sell them). In 2005 the first Arduino boards were released and they were an extremely inexpensive ($30-$40) way for hobbyists to start doing embedded programming.
The team who created the Arduino chose to base it upon the Atmel chips for numerous reasons including:
- low price
- easy to upload programs (flash memory)
- easy to write programs for
- provided a good set of functionality built-in (serial communication, etc.)
- performs well
Previously if a hobbyist wanted to do a simple project based on a microprocessor there might be hundreds of dollars of investment just to get started to program a chip. The Arduino and Atmel chips drove this price down significantly. Also, because the Arduino development boards were open-sourced anyone could build them and sell them driving the price down further.
The ATMega328 Has Everything We Need
Low Price
I bought two of these chips for only $10.99USD at amazon : Amazon.com: 2-pack NEW Atmega328p-pu Chip w/ Arduino UNO Bootloader[^].
Easy Serial Communication
The functionality of chips must be easily accessible via their pins and the ATMega328 has serial communication built-in and easily accessible via two pins : Transmit (Tx) and Receive (Rx). Here's a diagram of the chips pins and the names of those pins so you can see the serial pins. (Diagram from Atmel docs: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Summary.pdf[^])
You can see my highlight (red box) of the two serial communications pins marked as TXD and RXD on the diagram above.
Here's what one of the 28 pin ATMega328P chips looks like:
Very Easy To Wire Up To Bluetooth
As we will see, those pins make it extremely easy to wire up our chip to the Bluetooth module so we can read data from Bluetooth and send data back over Bluetooth. It will be a simple matter of connecting a wire from Tx of Bluetooth to RXD on chip and Rx of Bluetooth to TXD on the chip.
Let's wire up the power to the ATMega chip and the Bluetooth module and then write a C program that we wil flash to the chip which will grab the data from the Bluetooth device.
Wiring Up The Flash Programmer
The first thing we need to do is wire up our board so that we can flash our program to the chip -- write our program into the flash memory of the ATMega chip.
Normally this is where we would be talking about some Arduino programming board. However, I am frugal (cheap) and I want to get down to the bare metal of the chip and program with straight C so I'm opting to use a different device.
I suggest you get the following flash programmer which works extremely well and is inexpensive ($10.50USD):
Amazon.com: Gikfun USBASP AVR Programmer Adapter 10 Pin Cable USB [^]
Setting Up Your Flash Programmer
Get The Drivers
You connect this device to your USB port and install some drivers available at:
USBasp - USB programmer for Atmel AVR controllers - fischl.de[^]
Get and Install AVRDude
Next, you install AVRDude which is the software which will compile your C programs using the GNU C compiler and will then flash the program into the memory of your chip.
You can get AVRDude (free and open source) at: Index of /releases/avrdude[^]
Grab the latest release, download it, unzip it and then you'll be able to run AVRDude at the command line.
Challenges To Setting Up Environment
I understand that there are some challenges to setting up this programming environment but in an effort to keep this article shorter I won't go through all of those. Later I will add some articles to my blog which will offer help to any of you who get stuck working through this. Check out the top of my blog landng page at RAD Dev US - Blog - Roger Deutsch's Dev Site[^] for more details. Note: It won't be available at the time this article is published because it will take me some time to write up those articles.
Great Resource For Getting Setup
The book I read to get through all of this and begin programming Atmel chips is : AVR Programming: Learning to Write Software for Hardware by Elliot Williams, eBook - Amazon.com[^] You don't have to read the entire thing though it is a very well written book. The first two chapters will get you all setup if you need more help.
I'll assume that you have your environment set up and connected and you're ready to flash a program to the chip.
C Program To Read Bytes From Bluetooth Module
Here's the simple program that I use to read the incoming bytes from the Bluetooth module and then determine what we should do based upon the data.
#include <avr/io.h>
#include <util/delay.h>
#include "pinDefines.h"
#include "USART.h"
int main(void) {
char serialCharacter;
DDRB |= 0b0000001;
initUSART();
while (1) {
serialCharacter = receiveByte();
transmitByte(serialCharacter);
if (serialCharacter == 'y')
{
PORTB = 0b00000001;
}
if (serialCharacter == 'n')
{
PORTB = 0b00000000;
}
_delay_ms(100);
}
return 0;
}
Close Examination of AVR C Program
Let's go through the code step by step and explain what the simple code does. This code comes from an altered version of Elliot Williams (author of previously mentioned AVR Programming book) code which can be found at his GitHub : AVR-Programming/serialLoopback.c at master · hexagon5un/AVR-Programming · GitHub[^].
Get the Entire Project In One Zip
You can download the entire project which is nicely zipped up for you in one folder at the top of this article (ActivateDoor.zip). That zip also contains a makefile for the project and if your GNU C toolchain is setup properly (if you instaleld WinAVR it is) then you'll be able to type : c:\>make
and the project will build and output the activateDoor.hex (which is the file which gets uploaded to the ATMega328P chip).
Include Files
The first four lines you see in the code are the references to the libraries that this program use. The ones which are shown between the brackets are ones that are part of the AVR-C standard library or just the C standard libraries. They are a part of your WinAVR installation and the GNU C toolchain.
The other two (pinDefines.h and USART.h) are add-ins for this program. I got these from Elliot Williams' github because they provide some functionality that we need to read and write on the serial pins (Tx and Rx) on the ATMega328P.
Using the makefile (again provided by Elliot Williams) helps also because if we type
c:\ActivateDoor>make flash
then the GCC compiler will follow the make script, build the executable (.hex file) and flash it into the chip's memory all at once. This process isn't always easy so I'll write some supplemental blog entries at my site about traps and pitfalls that occur which will hopefully get you past any problems.
The first thing the code does inside the main() function is set up a variable to hold a character that we will read from the RXD pin. That will be the value that something sends to us via Bluetooth.
Set Output Pin
Next you see that odd line of code :
DDRB |= 0b0000001;
That simply means prepare PORT B pins for output. This line uses a bit operator to set the first bit of that Port B to have a voltage. That indicates to the chip that the pin is available for writing to. DDRB bit 1 is equal to PB0 (pin number 14 in the diagram which shows the pin labels above). Again, setting this value, just prepares the chip to know that it will be used for output. It doesn't set the value yet. We'll see that in a moment.
Initialize Serial Pins
We also have to prepare the serial pins for sending and receiving and luckily that code is already written for us so we don't have to figure it all out. The code in the usart.h
library and the actual implemention of initUSART()
is found in the usart.c
file which is included in the project zip. We don't have to think much about it since all that work is done for us.
Now, before I explain the infinite while loop that comes next, let's take a step back and think about the fact that the chip we are using is a complete computer. Here's what I mean.
Overview of AVR Chip As A Complete Computer
If you take our ATMega328P chip and wire it's pins so that the VCC (pin 7 in our diagram) is wired up to 5v and the ground pin (pin 8 in our diagram) is wired up to ground the chip will start running whatever program has been flashed into its memory. That's right, without anything else even attached the chip will start processing. However, there may not be a program flashed to the chip's memory. And, even if there is, if there is nothing attached to its output pins there is no way for you to know that it is doing anything.
As Long As There Is Power, It'll Run the Program
My basic point here is that as long as there is power, the chip will run the program. That's why we put our program into an infinite loop with a while statement something like the following line:
while (1) { //do something... }
That simply means while true keep looping over these lines. That simply creates a program loop that will run as long as their is power on the chip.
The first line inside our loop is:
serialCharacter = receiveByte();
We are calling one of the pre-written usart functions and asking it to grab any byte (character) that is received and store it in our char
variable.
The next line in the code is a bit odd.
transmitByte(serialCharacter);
We then transmit that character right back out using another library function. That's simply because I was attempting to make sure I could see the characters I had typed echoed back to me on the terminal screen I was using to test my program.
The Interesting Code That Does Something
Finally we get to the interesting code that actually does something. It is the core of our entire system and is how we are linked to the Android program. (Later, we will see how our Android program sends character values to our Bluetooth module.)
When the character comes in we check it's value. If it's the letter Y we turn on voltage on PB0 (Pin 14), if it's an N we turn voltage off on PB0.
if (serialCharacter == 'y')
{
PORTB = 0b00000001; }
if (serialCharacter == 'n')
{
PORTB = 0b00000000; }
PB0 (Pin 14) Is Directly Connected to Input Port On Relay
Now that you see that code, you can see how that the entire thing works. Since PB0 is connected by wire to the Input port on our Relay it controls when the relay switches.
Of course, when the relay switches, the output circuit is activated and the switch on the ODM (overhead door motor) is closed and the motor is activated.
Android App, We Need You
Now, all we need is the Android app which allows us to pair up with our Bluetooth module so it can send the values to set PB0 high and low to activate / deactivate the switch.
To get the Bluetooth Android app working, I completely depended upon the official Google documentation at : Bluetooth | Android Developers[^]
You can download the Android app at the top of this article and build it with Android Studio.
Download APK - Android Install Package
Or if you want to, you can download the app directly from my website onto your phone or tablet for installation.
Just point your device's browser at : http://raddev.us/android/btfinder.apk[^] Once you download it, you can install it very easily by tapping the file. It only requests rights to control / setup Bluetooth so it is not too instrusive.
Android App : Drafty Version
I was going to clean up the app UI for this article but I've decided to give you the rough version of the app so you can be closer to the metal of what development I did.
The app looks like the following:
Basically, the app allow loads a list of paired Bluetooth devices at the top.
To connect to your Bluetooth module after you've powered it up, all you have to do is touch it where it appears in the top list.
When you touch the item in the list, the app will send some test data to the Bluetooth device and provide you with a message to let you know if it succeeded.
Whether it succeeds or fails then it will print a message in the bottom scrollable list so you can know the status.
Somewhat Manual Operation
If the initial connection succeeds, then you'll click the [Yes] button to send the y which will activate the Relay. However, right now you need to deactivate the relay manually so after you click the [Yes] button, go ahead and click the [No] button.
Each time you click a button, a new status will be written to the bottom scrollable list view so you know that the app has taken the action.
Android Development Challenge: No Emulated Bluetooth
One of the main challenges of developing the Bluetooth app is that there is no emulation provided for Bluetooth on the Android Emulated devices. That means the only way to test the app is to send it to a device, run the app and see what happens. That's why I have all these status messages written to the scrollable list view.
When you start the app it will look something like the following: (of course this was run on the emulator but imagine each of those test items is a Bluetooth device)
One of those items will most likely be named HC-05 (our Bluetooth module).
Next, you would just tap the item in the top list and the app will attempt to connect to the device and send some data as test.
It will fail on the emulator, but at least it gives you some output so you know.
If you run the app on a real device and it connects properly it will look something like the following:
Finally, after you get you connect successfully you click the [Yes] button and the PB0 pin will go high (be set to 5v) and the relay will activate.
To keep it shorter (too late :) ), here is the code in the ConnectThread.java class that writes the y and the n.
public void writeYes() {
try {
byte [] outByte = new byte[]{121};
mmOutStream.write(outByte);
logViewAdapter.add("Success; Wrote YES!");
logViewAdapter.notifyDataSetChanged();
} catch (IOException e) { }
}
public void writeNo() {
try {
byte [] outByte = new byte[]{110};
mmOutStream.write(outByte);
logViewAdapter.add("Success; Wrote NO");
logViewAdapter.notifyDataSetChanged();
mmOutStream.write(outByte);
} catch (IOException e) { }
}
You can see we set the outByte to ascii value 121 for a lowercase y in the writeYes()
method. And we set the outByte to 110 for lowecase n in the writeNo()
method. It's as simple as that.
You can also see that the app writes a short message letting you know it wrote bytes to the stream which is written out on the Bluetooth signal.
Quick List of Required Components
- Bluetooth module (HC-05) - Amazon.com: HC-05 Wireless Bluetooth Serial Transceiver Module Slave And Master[^]
- AVR Chip : ATMega328P - - Amazon.com: 2-pack NEW Atmega328p-pu Chip w/ Arduino UNO Bootloader[^]
- Relay module - Amazon.com: Tolako 5v Relay Module for Arduino (Works with Official Arduino Boards)[^]
- Breadboard for easy circuit building - Amazon.com: Frentaly® 3x Solderless BreadBoard, 400 tie-points[^]
- assorted wires
- LED for power status
- 220 Ohm resistor (used in line with LED)
- 22 pF disc capicator to even out power
- power adaptor / transformer so you can easily plug into A/C - I used an old motorola Razr charger I repurposed for this, but you need one that outputs 5v and around 850ma of current. - Amazon.com: Motorola SPN5202B 5V 850mA AC Adapter Power Supply for Motorola RAZR[^]
Points of Interest / Caveats
My initial intent with this article was to show you that you can make build this project even if you have little experience with all of the various parts (AVR chips, Bluetooth, Android). I still believe you can if you follow the steps in this article.
Difficulties Are With Setup, Not Necessarily the Details of the Project
I found that the details of this particular project are extremely easy. It's an extremely easy thing to do over all. The challenges you will most likely encounter will be related to getting your build system all set up. Getting WinAVR installed and building your AVR-C programs and then flashing those programs to your AVR Chip can be extremely difficult so don't become too frustrated thinking you are doing something wrong that is easy. It is not easy at all. And it can be extremely frustrating since you can have on little thing set up incorrectly and nothing seems to work.
Don't Give Up
Even if it gets difficult, don't give up. Everything you learn will help you through to the next project.
As I've mentioned I will attempt to write some articles at my site (RAD Dev US - Blog - Roger Deutsch's Dev Site[^]) to detail these things further and lend a helping hand.
Comment and Ask Questions If You Need Help
I hope you can see I"ve put a lot of work into writing this up. And I hope that you'll comment and request help if you need it, because I am glad to help you get your project going in any way I can.
Connecting Relay to ODM Wires : The Failure
Which Side: Normally Open Or Normally Closed
When I first connected the output wires to the ODM I had them connected to the common and the NO (Normally Open) side of the relay. I figured this was correct because I figured that the switch would have no voltage on it and then we would apply voltage to it.
Wall Switch Stopped Working!?!
It worked completely as expected via the Android app. However, the wall switch no longer functioned. I also noticed that the led on the wall switch was no longer lit up. I should've investigated further but I was too excited because my app worked and I could open / close the door from my phone.
Ohter Remotes Also Stopped Working
Then my wife tried to leave. She couldn't open the garage door from the wall switch so she got in her car and figured she could use the normal R/F (radio frequency) remote she has. Nope! The problem was that the circuit actually needs some current running on it that the ODM provides to light the status led on the wall and to allow the R/F remotes to work.
I took a guess and switch my output wire to the NC (normally closed) side and the wall switch led turned on immediately. The wall switch started working again and so did the R/F remotes.
The interesting thing is that the app now turns the switch off for a moment and then re-connects it to the NC side again. It's the opposite of how I thought it might work but the good news is that the app and all switches now work great.
History
First published 07-27-2016