Fads to Obsessions and Beyond...

Free domain for life, exceptional technical support, website transfer

Bluetooth Garden LED Lighting

Garden lights for illuminating a walking path are made from six salvaged high current LED's and controlled via Bluetooth/PIC microcontroller. The lights automatically turn on and off at night via a user-controlled schedule that can be updated via Bluetooth and Android Phone App. Additionally, a LDR as light sensor (with adjustable sensitivity and then turn-off after a preset time, variable up to hours) is included. The circuitry is powered by 12V DC battery/solar power recharge. Battery voltage (with low voltage cut-off to prevent over-discharge) and light level can also be recorded (at user determined intervals) to non-volatile memory and downloaded via Bluetooth to SD card. See this Garden Light Project for a version using "analog" circuity without the need for a microcontroller.

A discarded emergency beacon that was found at a rubbish dump contained six high current LEDs (see Photographs Section) which were still operational. Testing of the salvaged LED's showed they have a forward voltage of ~1.6V and even with a relatively modest current of 0.25A were very bright.

The rear garden of my house has a walking path with a set of stairs leading to a side entrance, which has resulted in a number of falls when being used at night time. The salvaged LED's are bright enough to more than adequately illuminate this path. In order to quickly produce a working prototype of a circuit to utilise these LED's to illuminate the garden path, a version was produced that did not involve a microcontroller (see this link for details).

The initial "analog" version is powered by a 12V battery, that is recharged by a small solar cell/regulator. In order to minimise current draw, the LED's turn on automatically at dusk and then turn off again after a preset amount of time, seven (7) hours in this case. At my location, dusk is generally between 6pm and 7pm, which with a seven hour LED 'on time' results in the walking path being automatically illuminated from sun-down to between 1am-2am in the morning. In order to achieve greater battery life (and allow for lower amounts of solar recharging due to shading/poor weather etc) pulse width modulation (PWM) of the LED's is used (a ~50% duty cycle).

New Improved Version

It was initially desired that the garden lights could be automatically turned on via ultrasonic sensors acting as a 'trip wire', placed at the start and end of the path. This would allow the LED's to be easily turned-on at the location needed without the need for "manual" switches to be installed on walls etc. Thus enabling the illumination to be present only when required (and hence maximise battery power).

However, this requires a microcontroller/code and the circuitry to provide an ultrasonic pulse and detection. As previously mentioned, considering that a number of falls on the garden walking path had already occurred at night time, it was decided that an initial 'version 1.0' of the garden path lights would only involve light sensing to automatically turn-on the LED's and the timer function to turn-off the LED's after the preset amount of time. This limited set of functionality would enable the lighting of the garden path to be achieved more quickly. The incorporation of an ultrasonic sensor to provide additional functionality or options for illuminating the LED's would be 'version 2.0'.

The major objective of 'version 2.0' is to enable a user to turn-on the LED's when required, without resorting to using switches etc mounted on walls (which in the dark can be diffcult to locate in themselves, let alone the difficulty/expense of wiring and mounting). That is, the LED's "sense" when a person is in the vicinity and if also "dark" turn-on the LEDS to provide illumination.

A HC-SR04 ultrasonic sensor inconjunction with an appropriate light sensor meets these requirements and was initially explored (link here). However, I became aware of the HC-05 Bluetooth Module which proved relatively easy to use and incorporate into DIY circuits. This link presents the results of testing the HC-05 Bluetooth Module.

The use of an ultrasonic detector or Bluetooth control would require a microcontroller to be incorporated into the control circuit in either case. A PIC16F772 was to be used (provides a number of ADC inputs, PWM modulation output, I2C connectivity and USART for RS-232) as I fortuitously purchased twenty for a dollar each from a discount online vendor. The use of Bluetooth connectivity means that no hardware (sensors, switches, wiring etc) would be required and a user could control the LED garden lights remotely (e.g., from inside a vehicle approaching the garage) up to the limits of Bluetooth (with the HC-05 I typically achieve 15-20 meters).

Rather than make a "transmitter" and "receiver" using two HC-05 units and associated circuits, the HC-05/circuit used to control the garden LED lights is in "slave" mode, and is controlled via an Android based cell-phone and associated app. Android Studio is a freely available Java based programming environment (IDE) that enables apps to be relatively easily produced and uploaded to Android based cell-phones, without requiring a "developer account" and the associated fees etc.

New Improved Version Details

Therefore, 'version 2.0' of the Garden LED Light Project uses a Samsung (or similar) cell-phone to remotely control the operation of the LED garden lights/circuit, having the following functionality:

  • Real-time clock (RTC) function for timing of LED on/off periods and time-stamp of recorded data
  • LED's on/off periods can be programmed via Bluetooth/Phone App into non-volatile EEPROM memory
  • "Emergency" over-ride function to immediately turn LED's on/off via Bluetooth/Phone App
  • Use of Pulse Width Modulation (PWM) to maximise battery powered operation
  • Constant current source for powering LED's
  • Incorporate light sensor (light dependent resistor LDR) as alternative mode to control LED operation
  • Monitoring of battery voltage to stop over-discharge of battery (op-amp circuitry to enable 0.1V resolution via 10-bit PIC onboard ADC)
  • Battery voltage and or light sensor level data can be stored (at user determined intervals down to 1 minute) to non-volatile EEPROM memory, and downloaded via Bluetooth/Phone App to SD card
  • All variables (PWM settings, light sensor sensitivity, timing, data logging, scheduling, RTC updating) can be performed via Bluetooth/Phone App
  • Firmware can be updated via ICSP to enable later change to functionality

See the various sections below for circuit details, schematic diagrams, software/firmware and other details.

The schematic for the SMPS power-supply and the microcontroller I/O components is given in the Schematics Section below. The ancillary circuitry includes reverse-polarity protection, monitoring of battery-voltage to avoid over-discharge, EEPROM for external non-volatile memory storage and PWM/Constant current source for powering LED's.

Power Supply

The circuit and associated LED's are to be powered by 12V DC battery (a sealed 'motor cycle' 15Ahr battery) that is recharged by a small solar cell/regulator. The PIC16F722 operates from 1.8V to 5.5V, whereas the HC-05 operates at 3.3V. Therefore, operating the circuit with Vdd of 3.3V is advantageous. The DC-DC conversion could be handled by a linear regulator such as the LM317 but this is wasteful of electrical power, particularly in this battery operated situation.

An alternative to DC-DC conversion via linear regulator IC's is to use a switching regulator to form a DC-DC step-down (called a "buck converter") switch-mode power supply (SMPS). A SMPS uses a switching transistor to alternately power the load via the source DC and a combination of an inductor and capacitor (which are also "charged" by the source DC) (1). This enables a more efficient use of the source DC and less wastage of electrical power as compared to the "usual" linear voltage regulator method.

A LM2596 SMPS is used to provide the DC-DC conversion from the battery voltage (12-13.5V, below 12V the circuit cuts-off supply to avoid over-discharge of the battery) to a nominal 4.5V, and then to a LM1086IT to produce 3.3V. The LM2596 incorporates thermal shutdown and current limit protection. The LM1086IT is not really required (at least for the limited testing performed) but is used to ensure a low-ripple supply for the microcontroller (as the LM2596 SMPS output has a ripple of ~ ±50mV).

Reverse Polarity Protection

The circuit will be connected to the battery using just standard electrical wiring (no polarised connector available). This means some form of polarity protection is necessary, as "insurance". There are three simple methods for polarity protection (diode, PNP transistor and P-channel FET - see this reference for explanation of advantages/disadvantages of each approach (2)). A P-channel FET is used in this case (Q1 in the schematic) as this gives the lowest voltage drop and power consumption/heat wastage, important in a battery powered project.

Since the supply voltage (12V) is greater than the Vgs of the P-channel MOSFET (the IRF9540 has Vgs=2-4V) a zener diode and gate resistor is not necessary in this case to limit voltage between the FET gate and source. The IRF9540 Rds(on) = 0.2ohm which is relatively high. However, this is what was available at the time and with a typical measured circuit current of 0.5A (PWM maximum duty cycle, LED's on brightest) gives a power dissipation (i.e. loss) of 0.52 A * 0.2 ohm = 0.05W (compared to 0.75V * 0.5A = 0.375W if just using a diode for example).

Battery Voltage Monitoring/Over-Discharge Protection

Over-discharge protection of the battery supply is provided by monitoring the battery voltage using one of the on-board analog to digital converters (ADC) available with the PIC16F722. The PIC16F722 firmware is programmed to disable operation of the garden path lights high power 6 x LEDs if the battery voltage falls below 12V (i.e., no PWM signal is output). A hysteresis is included so that LED operation does not begin again until the battery voltage exceeds 12.5V (to avoid "oscillation" or flickering of the LED's due to battery voltage rebound at the set-point). Note that the microcontroller and associated ancillary circuitry (indicator LED's, sensors etc) continue to draw current if the voltage drops below 12V (measured as less than 0.05A). However, since the system is solar-charged, over-discharge of the battery is unlikely and does not warrent additional circuitry (i.e. expense).

While the battery over-discharge protection is relatively simple, being mainly handled by the firmware, there is additional circuitry (op-amp U4 and associated resistor network) in order to scale and amplify the battery voltage to better use the microcontroller ADC voltage/10-bit range to give higher resolution measurements.

The PIC16F722 provides an 8-bit ADC with allowable voltage range -0.3V to Vdd+0.3V (Vdd in this case being nominally 3.3V). The expected battery voltage measurement range is ~14V (fully charged) to ~11.5V (which is taken as the set-point for fully discharged). Therefore, a voltage divider (R1 = 3300ohm, R2=1000ohm, Vin = 14V .: Vout = 3.26V) would be a simple approach to modifying the input voltage to be within the allowable voltage range of the PIC16F722 ADC. This would give, using Vdd as the ADC Vref, 3.3V/255 ADC bits = ~13mV/ADC bit, which (using the voltage divider output voltage) would result in 11.5V equating to bit 206 and 14V to bit 251 (i.e., only using ~45 bits, ~18%, of the ADC range).

The op-amp (U4 in the schematic) setup as a differential amplifier enables utilisation of the full 256 bits of the ADC to measure the desired battery voltage range of 11.5-14V giving enhanced resolution. The utilisation of an op-amp differential amplifier for such a purpose is given in (3) upon which the following discussion is based.

The op-amp configured as a differential amplifier is given schematically in the following figure 1. This gives the following equation:

Vout =
Rf / Ri
* (Vtrim - Vref)


  • Vout = Op-amp output voltage (to PIC16F722 ADC)
  • Vref = Reference voltage 2.5V (from TL431)
  • Vtrim = Input battery voltage divided by potentiometer RV2

The potentiometer is set such that an input voltage of 11.5V (or whatever other set-value is to be trimmed/offset) at Vbatt results in 2.5V (i.e., equal to whatever is the Vref value) at Vtrim. Therefore, the op-amp will output 0V when Vbatt equals 11.5V or less. The value Rf/Ri is the amplification factor and the values for the relevant resistors is discussed next.

  • Figure 1: Op-Amp Differential Amplifier

    Op-Amp Differential AmplifierOp-Amp Differential Amplifier

    Silver Membership registration gives access to full resolution diagrams.

    Figure 1: Op-Amp Differential Amplifier

Taking the value of potentiometer RV2 as 10k ohm, and using the voltage-divider equation, when an input voltage of 11.5V results in Vtrim of 2.5V, an input voltage of 14V to RV2 would produce Vtrim equal to 3.05V. Therefore, the desired battery voltage measurement range of 11.5 to 14V (i.e. range of Vbatt) will result in a range of 2.5 to 3.05V for Vtrim giving a span of 0.55V. Therefore, 0.55V is required to be amplified (i.e. scaled) to the full range of whatever the value of the reference voltage in use (in this case 2.5V). Therefore, Rf/Ri = 2.5/0.55 = 4.54.

Determining values for Rf and Ri involves considering what are the standard available resistor values and that low-value resistors draw more current and load the opamp; while high-value resistors are noisy. Using the standard E12 series, values of 15/3.3 give the required result of 4.54 (a nice coincidence). The actual values choosen are Rf = 150k ohm and Ri = 33k ohm, to give relatively high input impedance.

The PIC16F722 onboard ADC is 8-bit, therefore, with the input battery voltage trimmed/offset by 11.5V and scaled to the reference full scale voltage of 2.5V, this gives a resolution of 2.5V/255 bits = 0.01V/bit (compared to 0.06V/bit if just using a voltage divider).

The use of the op-amp differential amplifier is arguably not warranted just for "battery over-discharge monitoring" and could be omitted from the circuit if cost is a particular concern. However, since logging of measured battery voltage is incorporated as part of the firmware, the extra resolution is "nice" and the exercise was a good learning opportunity.

If the op-amp differential amplifier is included in the circuit, the "calibration" procedure (i.e. input set known voltages and adjusting potentiometer RV2 etc) is given in the Construction Notes/Trouble Shooting Section.

PWM/Constant current source for powering LED's

The circuit used for the constant current driver for the LED's was sourced from an article by Giorgos Lazaridis (4). This circuit is also used in the strip lighting project except in this situation, pulse width modulation (PWM) of the constant current supply was included to decrease overall power consumption of the LEDs, as battery power is used.

With reference to the details in (4) and the components labelled on the diagram in the Schematic Diagram section. Output from the microcontroller pin RC2, through Q2 as an inverter to switch 12V from the battery via Q3, voltage is applied to the gate of MOSFET Q5 (the 12V was necessary so to be greater than the MOSFET Vgs of 2-4V, Vdd of the circuit/microcontroller is 3.3V). This allows current flow through the LED's and the sense resistor (formed by the combination of R17 and R18 - I did not have a "precision" 1 ohm resistor on-hand, and the parallel 10% 1 ohm resistors gave a resistance of ~1ohm).

As the current increases through the LED's and the sense resistor, the voltage drop across the sense resistor also increases. When this voltage reaches ~0.7V transistor Q4 starts to conduct, pulling the MOSFET gate to ground, and hence turning off the MOSFET. Therefore, current through the LED chain is regulated by the value of sense resistor.

To calculate the value of the sense resistor use the following formula:

Rsense =
Vbe / Iled


  • Vbe = base-emitter voltage transistor Q4 (~0.7V)
  • Iled = limiting current through LED (amps from datasheet)

The salvaged LED's used in the project were observed to be sufficiently bright with a current approximately 300mA. Therefore, the sense resistor value is 0.7/0.3 = 2.3 ohm. In the constructed circuit, the sense resistor is composed of the total resistance of R17 and R18 (which were 1 ohm 10% tolerance and gave ~1 ohm when measured in parallel).

The value of R16 is selected to enable ~1mA of current to flow to the gate of the MOSFET

The pulse width frequency of the PWM signal output from the microcontroller pin RC2 can be varied according to user selectable PWM settings via Bluetooth/Android phone app (I tend to use ~1000Hz, however any frequency above ~200Hz is sufficient to ensure "persistence of vision" effect in most people). Similarily, the duty cycle of the PWM signal is user selectable via Bluetooth/Android phone app, and this enables varying the brightness of the LED's.


The Testing/Experimental Results Section details the firmware (written in CSS C code) required to monitor the battery voltage, light level (LDR) and control the ancillary circuitry to power the garden path lights 6 x LEDs according the pre-set user input requirements and schedule (updatable via Bluetooth/Android Phone app).

Note: Image loading can be slow depending on server load.

  • I/O Controller SchematicI/O Controller Schematic

    Silver Membership registration gives access to full resolution schematic diagrams.

    I/O Controller Schematic

  • I/O Controller Schematic

  • Power Supply SchematicPower Supply Schematic

    Silver Membership registration gives access to full resolution schematic diagrams.

    Power Supply Schematic

  • Power Supply Schematic

Note: Image loading can be slow depending on server load.

  • Bluetooth Garden Lights - PCB Bottom Copper

    PCB Bottom CopperPCB Bottom Copper

    Silver Membership registration gives access to full resolution diagrams.

    PCB Bottom Copper

  • Bluetooth Garden Lights - PCB Silk

    PCB SilkPCB Silk

    Silver Membership registration gives access to full resolution diagrams.

    PCB Silk

See the Photographs Section (Album 3) for photographs of the DIY PCB fabrication through from UV exposure, then photo-resist developing, followed by cupric chloride etching and then "tinning" with stannous chloride to the final PCB ready for drilling/component soldering.

Qty Schematic Part-Reference Value Notes/Datasheet
1R110001/4W, 10% 
5R2,R4,R5,R12,R1510k1/4W, 10% 
1R32701/4W, 10% 
1R61501/4W, 10% 
1R71001/4W, 10% 
2R8,R1133k1/4W, 10% 
2R9,R10150k1/4W, 10% 
1R131.2k1/4W, 10% 
1R141k1/4W, 10% 
1R16100k1/4W, 10% 
2R17,R181 ohm1/4W, 10% 
2RV1,RV210K pot.potentiometer
1LDR1light dependent resistor
2C1,C2470uFaluminium or tantalum electrolytic
1D3bi-color LED (red/green)
Integrated Circuits
1U1LM2596SMPS  datasheet
1U2PIC16F722PIC microcontroller datasheet
1U324LC256EEPROM  datasheet
1U4TLC271Op-amp datasheet
1U5TL431Programmable voltage reference datasheet
1U6LM1086 3.33.3 voltage regulator datasheet
1Q1IRF9540p-channel MOSFET
1Q2-Q4BC547small signal transistor
1Q5IRF540Nn-channel MOSFET
1J1CONN-H55-pin connector for ICSP
1J2Test Pin1-pin
1J3SIL-100-06100 pitch, 6 pins
1Z1HC-05Bluetooth Serial Comms Module
Description Downloads
Bluetooth Garden LED Lights - Bill of Materials Text File Download

The first step in testing/developing the circuit is examination of the operation of the HC-05 Bluetooth Serial Communications module. Exploration of how to interface HC-05 Bluetooth Modules with PIC microcontroller via RS-232 communications is given here. The specifics of setting up individual HC-05 modules for use with the LED's (or any other circuit to be controlled via Bluetooth) is given in the following sub-section.

Details of the development of the firmware is also given below in the relevant sub-section.

The Video Section provides video clips of the completed circuit, both on breadboard during initial testing and PCB ready for deployment, in operation being controlled by the Bluetooth application running on an Android phone and tablet.

Testing HC-05 Bluetooth Module via TTL-USB Converter

The HC-05 accepts AT commands (when in command mode) which is useful to test if the module is powering up correctly in the first instance. A USB-TTL converter (I used a $2 converter purchased from ebay) makes it convenient to connect the HC-05 to a PC via USB (see the following photograph in Figure 1). The USB-TTL converter takes power from the USB socket (no other power supply necessary).

The initial step with the USB-TTL converter is to downloaded the necessary USB drivers (if using Windows) which I sourced from the Prolific Technology Inc site (5) which at the time of download was a file titled "PL2303_Prolific_ DriverInstaller_v1.12.0.zip". Unzip the file, click the installer and follow the usual steps for installing the driver software. When the USB-TTL converter is then connected to the USB port of the PC, Windows should do the usual driver installation steps.

The next step is to use a suitable serial port (COM) terminal emulation program to send commands to the HC-05 via the USB-TTL converter. I used "Terminal" which is very useful for debugging serial communication and is available for free (6) (download the zip file, unzip, and use the installer as usual for a Windows program).

The photograph in the following Figure 2 shows how the HC-05 is connected to the USB-TTL converter and then to the PC. In order to send AT commands to the HC-05 via the USB-TTL connection, the small-button on the bottom right-hand side of the HC-05 must be pushed when powering up (i.e. push and hold the button and then insert the USB cable into the PC USB port, when the LED on the HC-05 slowly flashs (~every 2 seconds) the button can be released.

With the USB-TTL connected to the HC-05 and the PC (and the HC-05 is in AT command mode) start the Terminal emulation program on the PC. Connect to the appropriate COM port (baud rate 38400, 8 bits, no parity, 1 stop bit). Enter the letters "AT" (without the quotes) into the transmit field (ensure the CR+LF is selected as equal to CR) and then click send. The letters "OK" should be received back indicating that the HC-05 is in AT command mode. You can then try other AT commands such as "AT+ADDR" which will return the device address of the HC-05.

Note that by using the push button on the HC-05 on power-up causes the HC-05 to enter "mini" AT command mode, which only allows a subset of the AT commands to be used (and a baud rate of 38400 is set and cannot be changed). There are a number of other methods with which to put the HC-05 into "full" AT command mode (which is necessary to use the NAME command for example) (7), but this is not necessary for basic usage. An alternative to "full" AT command mode, is to hold the push button on the HC-05 down while issuing commands. This works for the NAME command, which is useful as generally you want to change the name of individual HC-05 modules from the default "HC-05". Another useful initial command is "PSWD" which allows changing the password from the default "1234".

Success with getting the HC-05 to enter AT command mode and return information to AT commands means that the HC-05 is operational and ready for use in the PIC microcontroller circuit. Note the default settings for the HC-05 for normal communications (i.e. while not in AT command mode) is 9600 baud, 8 bits, no parity, and 1 stop bit.

  • Figure 2: TTL-USB converter connection to HC-05

    TTL-USB converter connection to HC-05TTL-USB converter connection to HC-05

    Silver Membership registration gives access to full resolution diagrams.

    Figure 2: TTL-USB converter connection to HC-05

Firmware Development

The software necessary for the project involves the firmware to be written to the PIC microcontroller (to interface the various hardware components such as analog to digital convertors for sensor input, RS-232 communication with the HC-05 Bluetooth Module, enable real-time clock functionality etc) and the software for the Android device/phone to provide the "app" that supplies the user GUI for control/updating of user input settings etc.

This sub-section discusses the firmware for the PIC microcontroller. A following sub-section details development of the Android device/phone app.

The basic outline of the PIC micrcontroller firmware is given by the following flowchart in Figure 3.

  • Figure 3: PIC microcontroller firmware flowchart

    PIC microcontroller firmware flowchartPIC microcontroller firmware flowchart

    Silver Membership registration gives access to full resolution diagrams.

    Figure 3: PIC microcontroller firmware flowchart

In relation to Figure 3, a hardware timer (timer1 module of the PIC16F722) produces "ticks" via a hardware interrupt, which are used to maintain a real-time clock (RTC) function (i.e. track the year, month, day, hour, minute and second). The RTC then enables the firmware to periodically check "scheduled" events (e.g. update sensor readings [battery voltage and light level] and if such readings need to be stored into EEPROM, and determine if the LED's should be illuminated or not according to the user input/stored time schedule). Data received via the HC-05 Bluetooth Serial Communications module is again hardware driven via interrupts to ensure no received data is lost. Upon receipt of data via the bluetooth serial communications channel, the data stream is decoded into the appropriate command. Finally, the results of the processing loop (i.e. assessment of "scheduled" events taking into account the current time, user input schedule, current voltage level and light level against received user commands and stored settings) are feed into a "state machine" which then illuminates the LED's as necessary.

Real Time Clock Function

Since a PIC16F722 was being utilised to interface with the Android Device/Phone App via Bluetooth/HC-05 module, a RTC function was implemented in firmware (rather than using a seperate chip such as the DS1307 RTC) to more fully utilise the onboard resources of the PIC16F722 and decrease part-count/cost. Further, since the circuit is battery powered, with solar charging, there was no particular benefit to including a DS1307 in this case (and the application is not "time" critical, so in the occasional event of changing battery and or low recharge due to adverse weather etc, re-setting the firmware RTC via the Bluetooth Application is not onerous).

Using the CCS C-compiler, setting up the PIC16F722 timer1 module (the timer2 module is required for use with the ADC - for interfacing the sensors for battery voltage monitoring and light level) is easily performed via the following code:

   setup_timer_1(T1_INTERNAL | T1_DIV_BY_8); //prescaler 8
   set_timer1(3035); //prescaler=8, 8Mhz, preload=3035 -> Freq 4hz, period=0.25sec

Upon power-up of the circuit, the RTC defaults to January 1st 2017 12 noon. The use of hardware interrupts for RTC timing and RS-232 communication and double buffering minimises the likelihood of data loss during receipt. Nevertheless, the firmware algorithm attempts to maximise the "cycles through the main loop" in order to make the application responsive to user input and avoid buffer overflow etc. Therefore, reading of sensors and checking of hardware status etc is staggered in timing to even out the processor load.

Sensor Input/Analog to Digital Conversion ADC

The monitoring of battery voltage (to enable over-discharge protection) and light level (via light dependent resistor LDR) is performed using the PIC16F722 on-board 8-bit ADC's. As discussed in the Circuit Details Section, an op-amp differential amplifier circuit is used to maximise the resolution available from the on-board ADC when monitoring battery voltage. The following code snippet demonstrates how the PIC ADC's are used to obtain sensor input:

   setup_adc_ports(sAN0|sAN1,VSS_VREF ); 

   //within CheckScheduledEvents()
      set_adc_channel(0); //channel 0 for battery voltage, channel 1 for LDR
      delay_us(10); //wait for ADC channel change
      adcBattery=Read_ADC(); //batteryValue = adcBattery * 0.008; //8bit - 2.048/255 = 0.008V/count
      if (batteryVoltageOkFlag) {   
         if (adcBattery < MIN_BATTERY_VOLTAGE_CUTOFF) {
            batteryVoltageOkFlag = false;}
      } else {
          if (adcBattery > MIN_BATTERY_VOLTAGE_RESTART) {
            batteryVoltageOkFlag = true;}    

Note the use of the #define's MIN_BATTERY_VOLTAGE_CUTOFF and MIN_BATTERY_VOLTAGE_RESTART. This provides a "hysterisis" so that LED operation does not begin again until the battery voltage exceeds MIN_BATTERY_VOLTAGE_RESTART (12.5V) to avoid "oscillation" or flickering of the LED's due to battery voltage rebound at the set cut-off point (MIN_BATTERY_VOLTAGE_CUTOFF = 12V).

Another item to note is that the firmware maintains sensor input as "raw counts" rather than converted to actual battery voltage. This enables the use of integer values to store the relevant variables in firmware, minimising microcontroller RAM use and the need for "multiplication" which is costly in terms of ROM (the PIC16F722 has limited ROM and no hardware multiplier support). Conversion of ADC "raw counts" is performed within the Android App (and or can be done with the downloaded data on a PC etc).

Pulse Width Modulation PWM

PWM is used to control LED brightness. The PIC16F722 has on-board support for generating and outputing PWM signals using hardware timer2. The following code snippet demonstrates the relevant CCS C code to enable and control the PWM signal:

   setup_ccp1(CCP_OFF); //start with PWM off 
   setup_timer_2(T2_DIV_BY_4,200,1); // PWM signal = 2500Hz with 50% duty cycle

   //within code
   setup_ccp1(CCP_PWM); //turn-on PWM signal i.e illuminate LED's
   setup_ccp1(CCP_OFF); //turn-off PWM signal
   case command_changeLEDbrightness:
         if (pwmRunningFlag==1) {
         } else {

Due to allowing the full range of PWM frequencies to be available to the user, a 16-bit integer is required to store the possible range of values for duty cycle. If a restricted (or pre-set) PWM frequency was used (anything over ~200Hz is sufficient for persistance of vision POV for the LED function), it would be possible to decrease the size of ROM and RAM usage somewhat. It was also found necessarily (not sure why) for the PWM signal to be stopped before changing the duty cycle.

State Machine (actual LED operation)

A "state machine" approach was taken for implementing the overall code. Even though the C compiler/PIC microcontroller does not provide much "native" support for a "state machine", the concept of "discrete states" (e.g. LED's being "off" and/or LED's being "on") and what "discrete events" (e.g. "low light level", "low battery voltage", "scheduled on" etc) affect which state is currently in effect was useful in developing the final firmware algorithm.

As mentioned, the C compiler/PIC microcontroller does not provide support as such for a "state machine". The actual implementation comes down to a series of CASE statements with nested IF THEN clauses that change the value of boolean variables ("flags" indicating the current status of "events" such as "low light level" etc), which then in aggregate determine which discrete state is in effect. For example:

void HandleStateMachine() {
   switch (LEDcurrentState){
      case OFF: if (batteryVoltageOkFlag && !(LEDmode == OFF)) {
                   if (LDRenabledFlag) {
                      if (LDRoverrideFlag) {
                         if (lowLightLevelFlag) {                           
                            changeState=true;} //change state to ON
                      } else {
                         if (LEDscheduledOnFlag) {
                            changeState=true;} //change state to ON
                   } else {
                      if (LEDscheduledOnFlag) {
                         changeState=true;} //change state to ON                  
                if (changeState) {

Android Phone/Device Application Development

I use Android based devices/smart phones as the free Android Studio IDE enables producing your own bluetooth customised app "relatively" easily, and does not require any initial cost outlay (assuming you have a PC and Android based smart phone or other device).

The first step is installing the Android Studio IDE which provides the software development environment necessary for implementing, testing and uploading a custom app to an Android based smart phone. Android Studio is developed by Google and is free with download and installation instructions located at this reference (7). There are numerous online tutorials teaching how to use Android Studio and the fundamentals of Android app development (8),(9). For those with prior programming experience, the Android Studio IDE and associated tools makes app development relatively straight-forward. While for those first time programmers, the Android Studio IDE and Java is a good starting point for learning in any case.

After having "mastered" the concepts of Android Studio and the framework behind Android based apps, the next step is dealing with incorporating Bluetooth functionality into an app. Again, there are numerous online tutorials and recommend the following reference as a starting point, which enables simply pairing the Android smart phone with the test circuit and toggling LED's (10).

Once completing this simple toggling of LED's on and off via Bluetooth and Android phone app, extending the concepts to produce the GUI for the LED garden lights is then just a straight-forward use of the various user interface elements provided by the Android Studio IDE, in-conjunction with the appropriate firmware code within the PIC microcontroller to act upon received data to control peripherals as desired.

I won't include any further detailed instructions about the Android Studio IDE, developing apps for Android based phones and or incorporating bluetooth communications funtionality, as there are already numerous excellent online sources, and the depth and breadth of necessary information really depends upon the readers prior experience and requirements.

However, for those with particular questions, please use the comments section below and I will attempt to answer your queries.

As a brief summary, the following is a "high level" overview of the components/approach used to produce the Android App that is used to control the LED garden lights:

  • An Android "sliding sidebar" (also termed a "hamburger" menu) is used for the main navigation method.
  • "Fragments" are used for each "screen" corresponding to a menu choice. This means bluetooth connectivity between "screens" is maintained (if an "activity" is used for each "screen", the Android life-cycle results in the bluetooth connection being lost when swapping between activities.
  • A Floating Action Button is used to show the "help" instructions.
  • A couple of noteworthy items:
    • The following line of code was required when writing received logged data to the phone SD Card file. This was to ensure that the filename appeared in Windows explorer, in the case that the Android phone was connected to PC via USB cable (and debugging mode enabled).
    • MediaScannerConnection.scanFile(getActivity(), new String[]{"/sdcard/" + strFileName}, null, null);
    • Ensure that the AndroidManifest.xml file contains "uses-permission" tags to enable bluetooth and use of phone external storage (SD card)


Description Downloads
text download to be included
text download to be included
text download to be included

The HC-05 RX and TX pins are 3.3V and therefore voltage conversion will be necessary if interfacing to a 5V microcontroller or similar (the PIC16F722 used in this project operates from 1.8V to 5.5V and so was used with Vcc=3.3V). A simple resistor voltage divider is sufficient for 5V to 3.3V when connecting the TX pin of the PIC microcontroller to the RX pin of the HC-05. It was found that no conversion was necessary for the 3.3V from the HC-05 TX pin to the RX pin of the PIC microcontroller.

As discusssed in the Testing/Experimental Results Section, the use of a USB-TTL converter to provide connection of the HC-05 to a PC via USB cable is useful for initial testing of the HC-05 module. This enables using a Windows PC terminal program to send AT commands to the HC-05 to test basic operation (and change default NAME and PASSWORD). This is very useful if there are any doubts about the quality of the HC-05 module and or if it has been powered up with incorrect polarity and or voltage etc.

The actual operation of the HC-05 in slave mode as a wireless serial communications peripheral (i.e. "wireless" RS-232) is relatively straight-forward (remembering HC-05 RX pin to TX of PIC, and HC-05 TX to RX of PIC). Note, there is no need for a MAX232 or similar as no voltage conversion from the RS-232 standard to TTL levels is necessary with the HC-05. The PIC microcontroller firmware only requires the standard USART routines generally available with various compilers, recommended with an interrupt driven approach for serial data capture using a circular buffer. Baud rates up to 38400 were tested (20MHz PIC) without apparent problems.

Development of custom apps for smart phone bluetooth communications to the HC-05 are relatively straight forward once the Android Studio IDE is installed correctly and the necessary plug-ins are downloaded. I find it necessary to start Android Studio (using Windows 8.1 on a PC) by right-clicking and "run as administrator" to ensure that the Android Debug Bridge (ADB) software is loaded/starts - which is necessary to upload developed apps to an attached device (e.g. Android phone). Finally, it is obviously important that an attached phone is in "developer mode" when trying up upload/debug software from Android Studio.

Calibrating the Opamp Differential Amplifier

Procedure for off-setting and scaling input battery voltage to maximise resolution of ADC readings:

  • Input the desired known minimum voltage (e.g. from a lab power supply) that will be trimmed/offset (i.e. substracted) from Vbatt at the "12V in" battery terminal (i.e. instead of connecting the lead-acid battery)
  • Measuring the output voltage at "test point 1" (i.e. the wiper of potentiometer RV2), alter RV2 until the measured voltage equals that being used for Vref (in this case 2.5V).
  • The microcontroller/Bluetooth App reports the ADC voltage reading corresponding to the measured battery voltage as "raw counts" (i.e. 0-255). In order to convert "raw counts" to actual battery voltage, use the following equation:
Vbatt = (ADC counts * 0.0098 V/count) + 11.5V

Note: Image loading can be slow depending on server load.

Album 1: Breadboard Testing

Album 2: Salvaged LED's

Album 3: PCB Fabrication

Note: Video loading can be slow depending on server load.

  • Video 1 below demonstrates the Bluetooth Application running on a Samsung Tablet controlling the circuit on the breadboard and operating the LED's.
  • Video 2 below demonstrates the Bluetooth Application running on an Android based phone (Alcatel Pixi). This is a screen capture (done with ADB) from the actual application running on the phone, showing the various pages/functions available.

Video 1:

Video 2:

ref001: http://www.learnabout-electronics.org/PSU/psu31.php

ref002: http://provideyourown.com/2012/reverse-polarity-protection-circuits/

ref002: http://www.computers-n-robots.de/mega8battMon/mega8battMon.html

ref003: http://www.pcbheaven.com/userpages/LED_driving_and_controlling_ methods/?topic=worklog&p=3

ref004: http://www.prolific.com.tw/US/ShowProduct.aspx?p_id=225&pcid=41

ref005: https://sites.google.com/site/terminalbpp/

ref006: http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-at-mode/

ref007: https://developer.android.com/studio/install.html

ref008: https://www.ntu.edu.sg/home/ehchua/programming/android/Android_HowTo.html

ref009: https://developer.android.com/training/index.html

ref010: http://diyhacking.com/arduino-bluetooth-basics/


No comments yet.

Add Comment/Question

Only Logged-In Members can add comments

"If we could sell our experiences for what they cost us, we'd all be millionaires".

Please donate any amount to help with hosting this web site.

If you subscribe (only $2/annum) you can view the site without advertisements and get emails abouts updates etc.



Only logged-in users with Silver Membership and above can download.

Silver Membership is only $2, so join now!