Saturday, December 23, 2017

Data from the light bulb

Once I read a blog post from Oona Räisänen that really inspired me. In her project she encoded a digital signal into the referee's whistle. I asked myself if there is any other household object that emits a radiation and could be used as a carrier for low-speed digital signal. I looked around and there was a light bulb.

Using light as signal transmitter is not at all a novelty. Beside all that optoelectronics stuff, recently Apple stirred some waves with their Li-Fi announcements that promises ultra-fast communication by means of a light bulb. I had something else in mind. I did not care about the speed, ad-hoc signal transmission of small data chunks that carry location IDs, sensor measurement was much more interesting for me. The use case would look like that you walk with your smartphone into a room lit by an innocently looking light bulb and presto, the smartphone picks up info from the light bulb without any special arrangement, e.g. you don't have to point your device anywhere. Speed and data size is of secondary concern in this use case which is a quite common scenario in the world of Internet of Things (IoT). Also, the light from the light bulb must look completely ordinary for human observer, e.g. no blinking, etc. This post is a tale of that adventure.

As I had prior experience with reading infrared signals from ordinary remote controls and sending them to the smartphone, I started with the method IR remote controls use to communicate with their receivers. Very shortly if you have not yet met this system: the emitter sends out period of "0s" (no light) and "1s" (IR light modulated by a certain frequency, typically 38 kHz). It is the length of these periods that carry the information. The common approach is that after a series of sync bursts, a digital 0 is encoded as a no light-light sequence of specified periods. A digital 1 is encoded similarly, except that the no light-light periods are different. You can observe this operation if you watch the light diode of an ordinary remote control through a smartphone camera. As the smartphone camera sensor "sees" in infrared (even though the manufacturers try to filter out this behaviour), you will see flashes of infrared light if you push a button on the remote.

Compared to the IR remote, we have an additional requirement: the human observer is not allowed to notice that the light bulb is doing something weird. For this purpose, I changed the modulation scheme. "No light" does not mean that the light bulb is switched off (that would result in a very annoying blinking sensation that humans are very sensitive to), only the modulation frequency is changed. In our system, the "light" periods are modulated with 38 kHz so that the popular IR remote decoder chips can be used, and the "no light" periods with 48 kHz. For the steep band pass input filters of those IR receiver chips, 48 kHz is essentially "no light". Considering the very noisy environment in the visible light domain, I also changed a popular IR modulation scheme, now the 0 bit is 564 microsec 48 kHz signal/564 microsec 38 kHz signal, the 1 bit is 1692 microsec 48 kHz signal/564 microsec 38 kHz signal. The whole payload is 20 bit long allowing to transmit a 16-bit value and a 4-bit data type selector. The data type selector lets the emitter send multiple types of data sequentially. In our demo, these are: station ID (for location), temperature and humidity (obtained from a DHT-22 sensor on the emitter board).

The system therefore consists of 3 elements: the emitter circuit that drives the light source, the adapter that receives these light signals and adapts them to the smartphone and finally the smartphone that acts upon those light signals.

  • In the prototype I am about to present the emitter is based on an Atmel Atmega328P microcontroller, in the form of an Arduino Pro Mini board.
  • The smartphone does not have light receiver and the Android application model cannot do real-time processing anyway so there is an adapter in between that on one side receives and decodes the light signals, on the other side interfaces with the smartphone by means of Bluetooth Low Energy (BLE). This element is implemented with two microcontrollers, an Atmega328P that does the real-time light signal processing and an nRF51822 SoC that deals with the BLE interface. As the nRF51822 is a quite capable ARM Cortex-M0 microcontroller, it is an interesting question why the light signal processing had to be offloaded to another microcontroller. The reason is the bad experiences I had regarding the real-time behaviour of the nRF51822 when its Bluetooth stack is operating.
  • The third element is a smartphone that connects to the receiver by means of BLE and displays whatever the adapter receives. This part is implemented in Android.
Let's start with the emitter. Below is the schematic (click to enlarge).

And this is how it looks like with the lighting LED beside the microcontroller card.

The source code can be found in this archive, in the light_sender/sketch subdirectory. You have to adapt the ARDUINO_DIR variable and probably the ISP_PROG and the ISP_PORT variables according to your programming tool. The AC input voltage may need to be adapted according to the lighting LED you choose. 38VAC effective value worked well for me for a wide range of lighting LEDs. The input voltage source also powers the microcontroller and this is really a sensitive area, I burnt a Pro Mini by screwing up something here. The problem is the large voltage drop hetween the LED supply voltage and the 3.3V that supplies the microcontroller. Before you insert the Pro Mini into its socket, make sure that VCC is 3.3V by setting TM1. Also, the Q2 FET has to be chosen carefully, the IRL540N type has drain-to-source breakdown voltage of 100V which is more than enough for this application.

The station ID (used for indoor location application) is hardcoded in light_sender.ino (STATION_ID). Optimally, every light bulb should have a different station ID.

Once the emitter is powered, it emits a steady 48 kHz signal which is "no light" in our encoding scheme. Every 1 second the emitter sends an encoded 20-bit value which is sequentially the station ID, temperature and humidity, the last two values are obtained from the DHT-22 sensor (U1). For the human observer, the light bulb is simply lit.

Now on to the adapter. Here is the schematic (click to enlarge).

And here is how it looks like.

The light receiver caused the most trouble for me. For starter, the photodiode required experiments. I played with 5 different diodes and eventually found the Osram SFH203 which worked well for me. If you cannot obtain this type, be prepared that you will also have to experiment. The next source of troubles was the IR receiver. Most IR receivers are integrated with the IR photodiode and these devices are made insensitive to visible light. Eventually I found VSOP58438 which has 2 problems: first it is obsolete and therefore it is hard to get, the second is that it is a 2mmx2mm square. Eventually my colleague helped me out and built a breakout board that you see in the foreground, with the Osram photodiode connected to it.

The rest is simpler. The Atmega328P (also provided in the form of an Arduino Pro Mini board) runs program that was originally designed as IR receiver. It can be found in this archive file (light_receiver/sketch/light_receiver.ino). The receiver library is Chris Young's IRLib with the timings modified for our modulation scheme. If the Atmega328P receives a value, it sends the value out on its serial output which you can observe SER_LIGHT_CODE pin.

The data goes into the nRF51822 SoC that I used in the form of a breakout board (here is an earlier post that describes the board and the development environment). Also, check out this post for instructions, how to compile and upload the project to the board. Here is the archive that contains the code for the nRF51822 SoC. The application in the nRF51822 SoC seems long but it is mostly boilerplate code, in reality its operation is very simple. Whenever it gets a value from the serial port, it writes that value into a BLE characteristic that has notification set. This means that whoever is subscribed to that notification, will get the event immediately, without polling the characteristic.

And finally, the reason why this topic is at all on an Android-themed blog: the detected values are consumed by an Android application. Click here to download the source code and read this blog post on how to convert the sources into an Android Studio project. The Android application is very similar with the previous ones, it scans for BLE endpoints with a unique UUID (274b15b0-b9cd-4e5e-94c4-1248b42b82f8 in our case) and when it finds one, connects to the endpoint using connection-oriented BLE. Then it subscribes to the light data characteristic (274b0100-b9cd-4e5e-94c4-1248b42b82f8) and when a new data comes from that characteristic, it evaluates the data type 4 bit and displays the lower 16 bit according to the data type.

Below is a small video showing how the thing works.

Observe the normal light sources and the small spot of smart light source that emits the data. The data is picked up from 3-4 meter distance.

Wednesday, June 14, 2017

Android weather station with a solar-powered BLE sensor

The ultimate test of the low energy consumption is a sensor that can survive on its own, without maintenance. My Android weather station supported by BLE weather sensors has been functioning for more than a year but this year has not passed without adventures in the battery front. First the station was powered by 2 AA NiMh batteries - that was 2 weeks of lifetime. Then came the motorcycle battery, that took much longer to expire but eventually the battery itself failed. Now the 2 sensors run on a discarded laptop battery which may not be able to power a laptop but powers nicely the two sensors with their combined 5 mA consumption.

5 mA, however, is a lot so when I found this solar-powered lamp at Jysk, I immediately realized that I had to turn the lamp into the solar-powered version of this weather sensor. Why another weather sensor? Because I wanted to concentrate on the solar-powering aspects and wanted to reuse as much as possible from the old sensor. This prototype may serve as a template, however, for different kind of sensors too.

Let's see first the solar lamp that I used as a base.

Solar lamp already containing the weather sensor. The two red LEDs indicate that the solar cell is charging the battery.

This is a quite cheap device with a solar cell on top and a circuit built around the XD5252F LED driver that takes care of everything from the charging of the small NiMh battery (if there's sunlight) to switching on the LED (if there's darkness). Unfortunately the circuit is so specialized to solar LED lamps that I could not reuse too much of it except for the solar panel and the LED itself. The solar panel is not very high-powered, it is a 2V, 20 mA cell. So it became clear immediately that the Android client app has to work more (consuming more energy) to obtain sensor data while the sensor has to sleep more to conserve its own battery that charges only very slowly from the low-powered solar cell. Also, surviving the night (or longer periods without sufficiently strong sunlight) requires a quite beefy battery in the sensor if we want it to transmit BLE messages to the Android application frequently enough.

Click here to download the sources of the Android application. Read this post to figure out, how to create an Android Studio project from the downloaded sources.

The previous Android app has been therefore changed so that instead of 15 seconds of scanning, it now scans for 70 seconds. The sensor sleeps 60 seconds then transmits the measurements for 5 seconds. This results in a quite low, 4 mAh energy consumption daily that even the low-powered solar cell can refill if sunny periods occur time to time. To make sure that the sensor survives long without enough sunlight, a 2700 mAh Li-Ion battery was installed (of the 14500 type, with the AA form factor). As in the previous version, the measurement data is transmitted in the BLE advertisement packets. I wanted to transmit battery indicator in this case too so I dropped one byte from the 8-byte long station ID (so it is now 7 bytes long) and instead of that byte now the supply voltage of the microcontroller is transmitted. It is generally 3.3V, if it drops below that then the battery is really not charging. This additional measurement data required that the sensor's UUID be changed, that's how the Android app recognizes this new parameter and displays in a graph.

Battery indicator in the measurement screen of the new sensor

The schematics of the sensor can be seen below (click to enlarge).

Sensor circuit installed into the solar lamp case

Nothing much changed from the previous version, except for the solar cell-battery charger power chain. I wanted to save myself the pain of designing a Li-Ion charger so I used building block already avalable: this DC-DC converter to produce 5V from the solar cell's varying output voltage and this battery charger circuit to take care of the Li-Ion battery. The result is a less than optimal efficiency (almost 50% of the solar cell's energy is lost during the different up-down conversions) but at least it is easy to reproduce. And if you like the sensor, you can always design a much better charging circuit. :-)

Click here to download the nRF51822 sources. Read this blog post for compilation instructions.

The nRF51822 microcontroller application has not changed a lot either. The most serious modification is the way the delays are implemented, now the sleeping periods between two measurements are implemented in a very low-power way and that results in a consumption in the inactive periods of about 100 microamperes.

And one thing more! Check out my low-cost robot project!

Monday, January 2, 2017

Adding more power to the BLE-enabled Christmas light

The truth is that the low-voltage LED strip I used in the previous post was a backup solution. Originally I bought a 230V-operated Christmas light with two independent LED strips but adapting that beast to Bluetooth Low Energy turned out to be a bit more problematic than I expected. I had to learn a bit about power electronics first.

My LED light I used as a base in this post is a standard-issue Chinese-made device. Below you can see how it looks like, its original controller already stripped of its plastic protective housing.

The circuit is very similar to this one, except that mine had only two LED strips, instead of 4. In my version the controller chip had HN-803 marking and the strip-controlling thyristors are of type PCR 406. The modes the original controller supported were all zero-crossing ones so I retained this operation.

Very shortly about the zero-crossing vs. phase-angle mode of controlling thyristors or triacs. A good introduction can be found here. The thyristor is fed with a current that has frequent zero-crossings. This is necessary because once the thyristor is switched on, the simplest way to turn it off is to remove the current on the load. That is why the Graetz-bridge converting the 230V alternating current into direct current does not have the usual filtering capacitors. This guarantees that the current feeding the LED strips/thyristors has zero-crossings with 100 Hz frequency. After the zero-crossing the thyristor can be switched on again by just a mA-range current applied on its gate electrode. The phase difference between the zero-crossing and the moment the gate current is applied determines whether we use dimming or not. Then the thyristor will remain switched on until the next zero-crossing. As the frequency of these zero-crossings is just 100 Hz, pulse-width modulation we used in the previous post for dimming cannot be used, the human eye would notice the flickering with such a low PWM frequency. So the simple circuit I am going to present here can only be used to flash the LED strips but not for dimming them. Implementing phase angle-based dimming would not be too hard with the features of our microcontroller but I did not want to get into that in this post.

Warning: part of the circuits described in this post use high-voltage 230 V current. Do not try to build them if you do not have experience with high-voltage electronics because you risk electrocuting!

Our exercise looks very simple. We need to remove the HN-803 controller circuit, replace it with our nRF51822 BLE SoC and use 2 of the output pins of the SoC to turn on the thyristors. Once the SoC drives the output pin to low, the thyristor will switch off at the next zero-crossing which allows us to flash the LED strips with frequencies lower than 100 Hz. Unfortunately nothing is simple if high-voltage current is involved because this simple circuit would connect the ground of the microcontroller board to a wire with high-voltage current (HVGND on the schematic) risking electric shock if someone touches the microcontroller board or ground-connected metal parts (like connectors) when the circuit is in operation. So I built an optocoupler-based isolator pictured below (click to enlarge).

The isolator ensures that the microcontroller-side has nothing to do with high-voltage current so no special precautions need to be done when handling the MCU board. The isolator itself, along with the remaining parts of the original controller circuit (D1-D4, T1/T2 and of course, LED1 and LED2 representing the two LED strips) are placed in a separate enclosure box. R3 dissipates around 1W so make sure that the resistor in question can withstand this power, I used a 2W resistor.

Driving the low-voltage side of the optocoupler still requires about 5 mA so I introduced additional FETs on the SoC side to provide this current. The updated circuit looks like below (click to enlarge). This circuit can control one low-voltage LED strip (with dimming) and two high-voltage strips (with no dimming) at the same time.

In my implementation the isolator and the MCU boards are located in two enclosure boxes which allows modular deployment - if there are no high-voltage strips then the isolator box is not needed. The connection between the MCU and the isolator boxes are 4 mA current loops which is quite resistant to noise. So the connecting cable could be  much longer than in the image below.

Now on to the software.

Click here to download the nRF51822 code.

Click here to download the Android code.

Compilation instructions can be found in the previous post. One warning: if you built the previous version and uploaded into the SoC, make sure that you mass-erase the chip ( script provided in the download bundle) and upload everything again (soft device and updated application) because the BLE service description has changed and the nRF51822 SDK writes data into the flash about the service characteristics.

Again I propose that before you start to experiment with the Android application, test the BLE device with a BLE debug tool like the nRF Connect for Mobile. You will see that the high-voltage LED strips are controlled by a new BLE characteristic (the old one controlling the low-voltage strip is still available unchanged).

The byte array written into this characteristic is a blob that describes the light effect. The blob has two identical sections, each of them 9 bytes long. One section starts with 1 byte for the repetition counter then 4 times 2 bytes, each 2 byte subsection having 1 byte for the time duration (in 0.1 sec units) and one byte for the bit mask of the LED strips (bit 0->1 if LED strip #1 is to be on, bit 1->1 if LED strip #2 is to be on).

Regarding the Android application, there are no too many surprises. I used the now deprecated TabActivity because I did not feel like playing around with fragments for this simple prototype. The screen has separate tabs for the low- and the high-voltage strips like this:

The disconnection deficiency described in the previous post is still there. Make sure that you disconnect from the device after each manipulation (by pressing the Back button) because neither the device nor the Android application implements disconnection timeout so if you stay connected, nobody else will be able to connect to the LED strip controller. Otherwise have fun with these BLE-enabled Christmas lights!