Rechargeable Motion Activated Light

I made this device for our driveway at the back of the house. There is a motion activated light near the back door but it doesn’t quite cover the driveway section because of a tree that’s on the way. So this presented quite a good opportunity for a side project.

The requirements

  1. Must be powered by a battery since no power outlet available.
  2. Motion activated
  3. Rechargeable
  4. Weatherproof
  5. Works only when dark

Motion detection can be achieved using a PIR (Passive Infrared) sensor. For this project I am using a PIR sensor I got from Adafruit. This sensor has a built-in signal processor, which makes using the sensor very simple.

This motion sensor runs on 5-12 V so I decided to use four NiMH rechargeable batteries. These batteries are 1.2 V each. For charging these batteries the easiest and most convenient solution is to use solar power. The solar cell I picked up from the local electronics store is rated at 100 mA at 7.2 V in full sunlight. Since the maximum amperage is lower than 1/10th the battery capacity (2500 mAh) I don’t need to worry about charge control circuitry (Check out this document by TI about battery charging).

So how to detect if it is dark? I am using a photocell for that. The resistance of the photocell increases as the ambient light decreases. By putting the photocell in a voltage divider the change in resistance can be translated into a change in voltage, which is used to control a MOSFET that drives the LEDs.

As with all my projects I first breadboard it to see if theory works as it should. If it works on the breadboard, there is a very good chance the actually circuit will work. As seen below in the schematic the circuit is quite simple. The schottky diode prevents current flow back into the solar cell, and also it has a very low forward voltage drop (~0.15 V) compared to regular diodes (0.7 V).



Schematic of the Rechargeable Motion Activated Light

Once I verified the circuit works on the breadboard the next step is to make a case for it. And that’s why I got my 3D printer. I designed this case to fit the particular fence we have in the backyard so it is not universal.

For the light, I decided to use the front section of an old LED flashlight. This gives a better beam for the light than making my own LED assembly. The photos below show the assembly of the device.


The main body that holds the circuitry and the batteries. I used enamel wire for connections because they are thin and insulated


The front and top sections showing the LED lamp, PIR sensor, and the Solar cell

After putting the case together and verifying everything still works the last thing to do is to waterproof it. Completely waterproofing things is very difficult. I used a glue gun to cover all open edges. This should keep most of the water out but time will tell if it will be enough.


The rechargeable motion activated light attached to a fence facing the driveway

And finally here’s a video that shows how this works:


New & Improved Gyro’clock case (V2)

Making the first version of the Gyro’clock case showed me some of its design flaws. Also I got to learn about some of the limitations of my 3D printer and 3D printing in general. So for the second version I have made the following improvements:

  1. Thickness of the walls increased to 2 mm to increase rigidity.
  2. Added a window for the switch and the charge status indicator LED.
  3. Replaced the top piece with a sliding door on the side. The sliding door doesn’t require any screws and fits snugly.

And here is the result


I am happy with this version of the case. Now I can actually carry around the Gyro’clock with me wherever I go. Gyro’clock is now complete. To wrap this all up I created a video about the project:



Asset Monitor

For the past three months I have been working on a school project. It is called an Asset Monitor. The Asset Monitor allows you to monitor your assets remotely through a smart phone.

The Asset Monitor consists of a network of Asset sensors that monitor the status of assets for motion and temperature. A central controller records all the data sent by all the Asset sensors, and forwards critical messages to the user’s mobile phone. Figure 1 shows an overview of the Asset Monitor.


Figure 1: Asset Monitor overview

The Asset Monitor has four major components:

  • Asset sensors
  • Controller
  • Google Cloud Messaging server
  • Asset mobile app

Asset sensor

An Asset sensor is a small battery powered device that is attached to the asset to be monitored. It monitors the asset for motion and temperature, and reports data to the controller periodically and in case of an event. The communication between the Asset sensor and controller is done using Bluetooth Low Energy (BLE).

BLE is a low power version of classic Bluetooth that is designed for low power applications such as battery powered sensors. The Asset sensors for our project are developed using the BLE121LR modules from Bluegiga. The BLE121LR module is built around the TI CC2541 microcontroller. The BLE functionality for the BLE121LR is already implemented by the BLuegiga software stack, and Bluegiga has also developed a scripting language called BGScript to program the modules. The main components of an Asset sensor are:

  • BLE121LR Bluetooth Low Energy module
  • MMA8452Q accelerometer
  • CR2032 coin cell battery
  • Push button

Figure 2 shows the prototype of an Asset sensor I have created.

IMG007 - Copy

Figure 2: Prototype of an Asset sensor

The motion detection is done using the MMA8452Q accelerometer. This accelerometer has a built-in motion detection capability, which can generate an interrupt signal when the acceleration exceeds a given threshold. This relieves the host processor from having to constantly poll the accelerometer for acceleration. The BLE121LR interfaces to the accelerometer using the IIC interface. Figure 3 shows a schematic of the Asset sensor prototype.


Figure 3: The schematic of Asset sensor prototype

The BLE121LR module has a built-in analog temperature sensor that can be used for temperature sensing. BLE121LR has a dedicated ADC channel to read the output of the temperature sensor. BLE121LR also has the capability to monitor its battery voltage. This is also done using the internal ADC.

Asset sensor firmware

The Asset sensor firmware is designed as a state machine. It can be in any one of five states at any given time as shown in Figure 4.

Asset sensor state machine

Figure 4: Asset sensor state machine

Asset sensor spends much of its time in the Idle state; the state that consumes the least amount of energy. To join a sensor to the Asset sensor network, it must be put on the Network Join state. This can be achieved by doing a two-button press (pressing the button twice within one second). Once joined to the network the sensor will wake up every second and increments a counter. If the counter matches the reporting interval (15 minutes), the device will read the temperature and battery voltage and enters the Report state, where it reports the data to the controller.

The Asset sensor firmware also supports message routing, which allows a sensor to act as a relay between another sensor and the controller. To join a sensor to the network through a relaying-sensor (parent device), first the joining-sensor (child device) must be put on the Network Join state. Then the parent device must be put on the Add child state by issuing a four-button press command. During the Add child state the parent device will automatically find and add the child device to the network.

Each sensor can support up to seven child devices. When one or more child devices are added to a sensor, it switches between the Scan and Idle states every second with a 10% duty cycle.  During the Scan state, the parent device is able to accept messages from a child device.

Figure 5 shows the packet structure used by an Asset sensor to report data to the controller or a parent device.

Advertisement packet

Figure 5: The advertisement packet used by an Asset sensor to report data

The type of packet used is a BLE broadcast packet, which is also called an advertisement packet. The firmware modifies the payload section of the advertisement packet to include battery voltage, motion status and temperature data. The device address helps the controller distinguish the data belonging to a child device from that of a parent device. A message id is added to help the controller eliminate duplicate messages. The advertisement packet can contain up to 37 bytes of data and can be easily extended to add additional parameters if necessary.

Motion detection

The flow chart in Figure 6 shows the steps used to configure the MMA8452Q accelerometer for motion detection.

Accel config flow chart

Figure 6: Flow chart for configuring the MMA8452Q for motion detection

Motion detection is configured on all three axes (x, y & z) of the accelerometer. The threshold is set to be just above ±1 g such that motion will not be triggered simply due to gravitational acceleration. The interrupt functionality of MMA8452Q is used to avoid the need for excessive polling by the CC2541 to check if motion is detected. In the interrupt mode, the accelerometer will generate an interrupt signal whenever the acceleration exceeds the set threshold value. The interrupt signal wakes up the CC2541 microcontroller so that it can report the motion detected event to the controller.

The motion de-bounce interval of 50 ms eliminates spurious detections due to noise. Once the CC2541 receives an interrupt signal from the accelerometer, it reads the motion threshold register of the accelerometer to clear the interrupt status. Three seconds after reporting the motion detected status to the controller, and if no other motion interrupts are received by the CC2541, then a no motion status is reported to the controller.

Temperature sensing

The temperature sensing ability of the Asset sensor is utilized from the built-in temperature sensor of the CC2541 microcontroller. The analog temperature sensor of the CC2541 is capable of monitoring temperature across the full operating range of the BLE121LR module (-40ºC to +85ºC). The temperature sensor outputs a voltage proportional to the temperature, which is read by the internal ADC of the CC2541. The sensor does not calculate the temperature with the ADC value, rather it sends the ADC result to the controller, and the controller performs the conversion from the voltage to the temperature in Celsius.

Battery voltage detection

In addition to motion status and temperature, the sensor also monitors its battery voltage level and reports to the controller. This allows the user to know when the battery needs to be replaced. Battery voltage detection is performed similar to the temperature detection. The CC2541 internal ADC has a dedicated channel for reading the battery voltage.

The Asset sensor is powered by a CR2032 coin cell battery. This battery has a capacity of 240 mAh and is rated for +3 V. However, when the battery is loaded with a circuit, the maximum voltage output of a new battery drops to around 2.65 V. When the battery is near the end of its life the output voltage drops to 2 V. The sensor reads and reports its battery voltage to the controller every 15 minutes.


The controller is the most critical component of the Asset Monitoring system since all messages from the Asset sensors must pass through the controller. This section provides an overview of the controller, its functionality and implementation. The main roles of the controller are to

  • Create and manage a network of Asset sensors
  • Record messages sent by all Asset sensors
  • Promptly alert the user of all critical messages

In order to carry out its duties the controller must have the following three key requirements:

  • Must support Bluetooth Low Energy
  • Must be connected to the internet
  • Must have a display for user interaction

For our project we used an old cell phone as a controller since it supports all three requirements above and can be easily programmed. A laptop, a desktop PC or a Raspberry Pi are all suitable choices for a controller. Figure 7 shows the cell phone that is used as the controller for the Asset Monitor.


Figure 7: A mobile phone is used as the controller since it has BLE and Wi-Fi

The controller application is simply an Android mobile phone application developed using Android Studio development environment. The controller must be connected to a Wi-Fi network with internet access. The controller application keeps the CPU of the phone awake at all times. Therefore, the controller must be connected to a power outlet through an adapter to provide a constant source of power.

Figure 8 shows the controller application window with two sensors connected to the network.


Figure 8: The controller application showing two sensors added to the network

The controller application allows the user to add sensors to the Asset Monitor network. When a sensor is successfully added to the network, it will appears as an item in the sensor list as shown in Figure 8. For each sensor, the controller displays the most recent data received from the sensor including temperature, motion status, battery status and the time of last report.

Controller software

The controller application must continuously listen for messages from child devices, since a sensor may report a critical message at any time. Before the controller is able to join devices to its network it must configure the Bluetooth LE adapter and register itself with the Google Cloud Messaging server. Figure 9 shows the initial configuration steps carried out by the controller application.

Asset controller startup

Figure 9: Flow chart showing the initial configuration steps of the controller application

After the Bluetooth LE adapter is configured, the controller app connects to the BLE service, a process that runs in the background, which provides BLE functionality to the app. Then the app registers itself with the Google Cloud Messaging (GCM) server and obtains a registration token. This step allows the controller to receive status update requests from the Asset mobile app. More information about GCM will be covered in the Google Cloud Messaging section.

The final configuration step is to start a repeating timer that periodically checks to see if the connected sensors are sending reports at regular intervals. If the controller has not received a message from a sensor within 17 minutes from the last report, an alert message is sent to the Asset mobile app. Once the initial configuration is complete the app simply waits for user to add sensors to the network.

User can add sensors to the network by clicking the Add Device button in the controller app. Figure 10 shows a flow chart of the process of joining a sensor to the network.

Add device flow chart

Figure 10: The flow chart for adding a device to the Asset sensor network

When the Add Device button is pressed, the controller app scans for network joinable Asset sensors and creates a list, which is presented to the user after the scan timeout occurs. The user selects a device for joining from the scan results list. Then the controller temporarily establishes a connection with the device, which indicates to the device that it has been added to the controller’s network. The sensor records the Bluetooth MAC address of the controller as the address of its parent. Afterwards the controller disconnects from the device and starts scanning for data reporting messages from the sensors.

When one or more sensors are joined to the controller, the controller begins to scan for messages from the sensors. Figure 11 shows the flow chart for scanning messages from connected sensors.

Asset controller scan messages flow chart

Figure 11: Flow chart for scanning messages from connected sensors

The controller only responds to messages from Asset sensors connected to its network. This allows two separate Asset Monitor systems to coexist at the same location. When a message is received from a child device, the controller responds with a scan request message. This message acts as an acknowledgment for the child device that the controller has received its message. If the message reported by child device is critical, such as a motion detected event, then the controller immediately sends a message to the Asset mobile app on the user’s cell phone via GCM server.

Sensor network topology

Figure 12 shows the topology of the Asset sensor network and two methods for joining sensors to the network.

network topology

Figure 12: The Asset sensor network has an extended star topology

Asset sensors can be joined directly to the controller or they may be joined to another sensor that is already joined to the network. This feature allows the range of the Asset Monitoring system to be extended beyond the maximum range of BLE. Each sensor has a parent device and may support up to seven child devices.

The direction of data flow is from a child device to its parent with the final destination being the controller. The child device does not receive data from its parent or the controller except for an acknowledgement that the data has been received.

There is no limit to the number of hierarchical levels that can exist in the network. However, adding more levels increases the network delay. Unlike the controller, a parent device cannot be listening to messages from child devices continuously as it significantly increases the energy consumption of the device. To conserve energy, a parent device scans for messages for only 100 ms and sleeps for 1 s before scanning again. Furthermore, a parent device only accepts a single message during scanning. So each level may increase the network delay by up to 7 seconds.

GCM connection server

This section explains how messages are exchanged between the controller and the Asset mobile app on the user’s mobile phone using Google Cloud Messaging (GCM). GCM is a third party service that is provided free of charge by Google Inc. to send messages between an application server and mobile devices. In our project, the controller or the Asset mobile app becomes the application server when one needs to send a message to the other. Some of the features provided by GCM include

  • Downstream and/or upstream messaging using HTTP or XMPP protocols
  • Group messaging for up to 20 devices
  • Maximum 4 kB of data per message
  • Store and deliver messages when devices are available

For our project we are using HTTP protocol since it provides the simplest implementation and does not require maintaining an active connection with the GCM server as in XMPP.

GCM service setup

Before using the GCM service both the controller and the Asset mobile app must register with the GCM servers. To register with the GCM service, a Google API project must be created in the Google Developers Console. The Google API project provides a project id and an API key. The project id is used during the registration process to identify a particular GCM enabled project. The API key gives access to the GCM service when a message needs to be sent.

After successfully registering with the GCM servers, the Asset mobile app subscribes to receive group messages. In GCM group messages (or multicast messages) are called topics. By subscribing to a certain topic, the mobile app receives all messages sent to that topic. Topics allow the controller to send only a single message rather than sending messages individually to all registered mobile devices.

The Asset mobile app subscribes to three topics: status, alarm and warning. The controller sends status updates of all Asset sensors to the status topic. Critical messages such as motion detection are sent to the alarm topic. Non critical alerts such as “sensor battery low” are sent to the warning topic.  When a message from a certain topic is received the Asset mobile app executes the appropriate course of action for that topic.

Similar to the Asset mobile app, the controller also registers with the GCM server, but subscribes to only a single topic: controller. When the user requests a status update from the mobile app, it sends a status request message to the controller topic. When the controller receives a status request message, it assembles the latest information from all the sensors and sends the data to the status topic.

GCM message format

When using the HTTP protocol a GCM message is sent as an HTTP post request to the GCM server. Figure 13 shows the structure of the message sent to the GCM server.


Figure 13: Structure of HTTP post request message sent to the GCM server

The HTTP post request sent to the GCM server contains a HTTP header and a HTTP body. The header contains the API key that is used to access the GCM service and the type of data contained in the HTTP body. The content in the HTTP body is of type JavaScript Object Notation (JSON). JSON is a data transfer format that arranges the data attribute value pairs. Each message contains an address specified by the attribute “to”. The address can be a registration token for a specific device or a topic in the case of a group message.

The optional attribute “priority” is used to indicate the urgency of the message. The GCM servers will attempt to deliver a message immediately if the priority is set to “high”. The “data” attribute is another JSON object that contains the message delivered to the recipient. The “data” attribute can contain up to 4 kB of data.

Asset mobile app

The Asset mobile app is the interface that allows the user to monitor his/her assets from any location. The only requirement is that the user’s mobile phone must be connected to the internet either through Wi-Fi or a mobile network. The Asset mobile app has two tasks:

  • Receive and display messages sent by the controller
  • Send status request messages to the controller and retrieve the latest sensor status

For our project we implemented the Asset mobile app for the Android operating system. A similar application can also be created for other mobile phone operating systems such as iOS. Figure 14 shows how notifications and sensor status are displayed to the user by the Asset mobile app.

Figure 14: The Asset mobile app showing a notification message and the sensor status

Figure 14: The Asset mobile app showing a notification message and the sensor status

The very first time the user executes the Asset mobile app, it registers itself with the GCM server to receive messages from the controller. The app initiates a process called GCM listener service that runs in the background, which periodically checks in with the GCM servers for any pending messages. If the GCM server sends a message, the GCM listener service receives the message and hands it over to the Asset mobile app. If the message is from the alarm or warning topics, the app assembles a notification message and displays it to the user. If enabled by the operating system the notification message will also generate an audible sound.

The user can request a status update by clicking the Refresh button (see Figure 14). When the refresh button is clicked, the app sends a status request message to the topic controller. Upon receiving the status request message the controller will send a message that includes an updated list of all sensors to the status topic. When the Asset mobile app receives a message from the status topic the app updates its sensor list with the latest information and displays it to the user.

And this is not so quick introduction to my latest project. If you are interested to learn more about the project and to see some of the results we achieved you can access the full report here.

Special thanks goes to my Local/Wide Area Networks instructor at BCIT, John Dian, for providing us with the Bluegiga development boards for this project.

Gyro’clock at the ASEE conference

Almost a year ago when I first started working on the Gyro’clock, My communications Instructor at the British Columbia Institute of Technology, Katherine Golder, told me about a Maker themed event that was planned for the Annual Conference of the American Society for Engineering Education in 2015. They were looking for people to come and present projects they work on that involves building things, you know, the kinda stuff we do. So I submitted my Gyro’clock as an entry and got the opportunity to go and demonstrate my project last week in Seattle!

There were 19 projects presented in total, and they were all unique and interesting. And it was great to get feedback from others about the Gyro’clock. I had an interactive setup, where they could see the centrifugal acceleration real time as I was spinning the Gyro’clock test unit. Also I brought along my old propeller clock to show the similarity and differences between it and the Gyro’clock.

As for my next steps, I am going to make the Gyro’clock into a real device that I can actually take with me when I go out. For this I have to make a PCB with surface mount components and also a suitable case for it. I have already gotten the components to build this more practical Gyro’clock. I will keep you updated as the work progresses.

Here are some photos from the ASEE conference, unfortunately I didn’t have enough time to get photos of any other projects, but you can see them here.

Also the paper I put together for the Conference is available here.

The interactive Gyro'clock poster

The interactive Gyro’clock poster

The propeller clock

The propeller clock

The two Gyro'clock prototypes along with the  first Music and Lights system

The two Gyro’clock prototypes along with the first Music and Lights system

I used the Music and Lights system to play a tone every time the Gyro'clock test unit is triggered.

I used the Music and Lights system to play a tone every time the Gyro’clock test unit is triggered.

Me at my table

The accelerometer output of the Gyro'clock was plotted real time and displayed on the computer screen

The accelerometer output of the Gyro’clock was plotted real time and displayed on the computer screen

Explaining the physics and engineering aspects of the Gyro'clock

Explaining the physics and engineering aspects of the Gyro’clock

Use the force!

Use the force!

2015-06-16 14.01.49 2015-06-16 14.01.53 2015-06-16 14.02.02 2015-06-16 14.02.10 2015-06-16 14.02.17 2015-06-16 14.02.24 2015-06-16 14.02.34

Hack it before Make it!

So I have written a paper about my experiments and the development of the Gyro’clock project, and it is going to get published in the annual conference proceedings of the American Society for Engineering Education (ASEE), SO EXCITED! I have been preparing for the poster session that’s going to be happening in June.

One of the attractions I am planing to have at my poster session is a counter that shows the number of rotations of the Gyro’clock. For this I need to figure out a way to make a cheap counter. Typically when you are going to make something you have to compromise between the cost and the amount of work. You can buy a LCD shield for you Arduino from Sparkfun at $13 and spend a few minutes writing a short program for it or spend an hour or two building a LED display for less than two dollars. BUT, there is way to have your cake and eat it too with making a counter. That is to hack it from a simple dollar store calculator and a MOSFET (or BJT) switch.

If you open up a cheap dollar store calculator, underneath the buttons you will see a set of traces. When a button is pressed it connects two traces together, depending on which button you pressed. The buttons are literally simple switches. So to make a counter all you have to do is:

1. Solder a piece of wire to each of the two traces of the equal sign button

2. Connect the two wires to a simple MOSFET switch.

3. Turn on the calculator, then press ‘+’ and ‘1’

Now when you close the MOSFET (or BJT) switch, the calculator will first display 1. The second time it will display 2. And the third time it will be 3! You just made, no hacked, the simplest counter in the world. And you can still use the calculator normally as you did before! Yes you can have your cake and eat it too!

So I already had a calculator lying around that could be hacked into a counter. After opening the back cover I found that this one takes cheap to a whole new level. The traces for the buttons are printed on paper in conductive ink! There isn’t even a PCB! There is a tiny PCB for the processor which is sealed with some sort of black goo. So obviously I can’t solder the wires to a paper. Instead I stripped two pieces of stranded wire and taped them into the two traces of the equal sign.

To wire it up with a MOSFET switch, connect one wire to the drain and the other to the source. You may have to switch the two wires around if the calculator doesn’t work (as it normally would) when you turn it on. That’s because there is diode junction between the body and the drain of an n-channel MOSFET, if the source is internally connected to the body of the MOSFET.

Connect the gate to an Arduino output pin. If you are using an n-channel MOSFET, a HIGH on the gate will turn on the switch. Add at least 50 ms delay between switch close and open, otherwise the calculator may not trigger reliably.

That’s it!  a simply hacked calculator counter! I made a video to show you how I am planning to use my counter in the conference. Hope you will find this useful someday,  and remember to Hack it before Make it!

PS: I didn’t invent this by the way. I saw it first in a youtube video while searching for how to program a calculator display.

Working Gyro’clock photos!

It has been a while since my last post (that was last year), but now I have pictures to show you of the new and much improved Gyro’clock. The key reason for the success this time around is using the transient detection function of the MMA8452Q. This is an embedded function of the accelerometer, which can be programmed to detect a change in accelerometer readings that exceeds a given threshold. That means the microcontroller does not need to constantly poll acceleration data. Instead it can let the accelerometer figure out when the threshold value is exceeded, and wait for it to send a signal. This improves accuracy significantly and saves a load off of the microcontroller.

Gyro'clock displaying time. The triggering accuracy has much improved since the last model

Gyro’clock displaying time. The triggering accuracy has much improved since the last model

I have also made a few modifications to the circuitry, mainly to reduce current consumption:

  • Added a bi-directional I2C level shifter to protect the MMA8452Q from the output voltage of ATmega328p, which can go above the maximum 3.6 V on a full charge of battery.
  • Added a 32.768 kHz crystal to improve clock accuracy. ATmega328p has a built in real time clock module (RTC), which uses this crystal as an asynchronous clock source. This also means that now I can put the microcontroller to sleep without losing time. Saves power!

The MMA8452Q accelerometer now has power only during the display mode and time set mode. The accel is disabled during idle mode bringing current consumption down from 2.2 mA to just 115 uA. At this rate, with a full charge of battery it will last for almost 40 days! (under testing)

Gyro'clock prototype with  changes to improve efficiency

Gyro’clock prototype with changes to improve efficiency

I have also made major changes to the code. But that has to be the subject of another post. There is still a bit more work to be done with the Gyro’clock. To reduce current consumption further, I want to make it go to sleep in between displaying the image. This is a bit tricky because waking up from an external interrupt seems to also trigger the timer overflow interrupt making the clock inaccurate. In the meantime here’s a video with the Gyro’clock in action:

A prize from ASIMOWALK5!

In the mail today I received a prize from a giveaway contest! It is an Attiny85 Programmer and Breakout Board from ASIMOWALK5.

Attiny85 Programmer/Breakout board by ASIMOWALK5

Attiny85 Programmer & Breakout Board by ASIMOWALK5

This is a neat little board that brings out the pins of the Attiny85 with clearly identified labels. With this board an Attiny85 can be programmed easily and quickly since you don’t have to keep looking up which pins to connect to. I haven’t used Attiny’s before so I am very excited to get one and try it out. The board also has room for a power input terminal and a power indicator LED, which is very handy. More information about this board and how to use it can be found here:

I already have a project idea in mind for this and the tiny Attiny85 would be an ideal choice! More on that coming soon in a future post, stay tuned!