# DIY LED lighting for 29G and some lens questions



## sink (Jun 11, 2011)

I'm in the process of setting an aquarium, my first since I was 10 and Bush Sr was in office. Lurking around here has been extremely informative. I got an old 29G (30x12x18in) and stand from a friend. I'm going to try a Walstad style tank with a soil substrate and lots of plants. Low tech except for the lighting--LEDs were just too interesting to pass up.

My design has 12 neutral white CREE XP-Gs driven by a homemade driver wired to a microcontroller. I've already built most of the driver and a hanging box (of very adjustable height above the tank) to house and hide the LEDs and heatsinks. The plan is two rows of 6 LEDs running the width of the tank. The driver, powersupply and microcontroller live in the tank stand.

I'd like some input before I buy the LEDs. Since these are questions I still have after a lot of reading, I hope any answers will be useful to others, too.

Intensity:
Will 12 XP-Gs be enough for this tank? I don't think I have very high lighting requirements. Most people use more relative to tank size but they seem to be doing high-tech, high-light tanks.

Color:
Everybody seems to do a mix of whites (cool/warm or cool/neutral) but I'm not convinced after looking at the spectrum graph for the white XP-Gs. I prefer a warmer look, plants grow fine under just about any reasonable spectrum, and I worry that with so few lights the staggered shades will be noticeable in the tank, especially with optics. I actually have a hunch that mixing whites is one of those things that somebody did once and everybody else has just been emulating without a thorough consideration of the merits.

Optics:
The fixture will be hanging, and while I know technically how optics affect the light spread, I'm not certain exactly how things will behave in practice when everything is set up with so few lights/area. A higher fixture with 40deg optics seems to be the way to go: Looks nicer from a design standpoint, easier water access, more uniform PAR between surface and substrate. But I'm concerned about having dark areas in the tank, especially near the surface. Anybody have experience with this?

Thanks!


----------



## O2surplus (Jan 31, 2010)

How much current do you plan to run through the XP-G's? I think 12 XP-g's will deliver enough par to grow most plants, if they're driven to at least 1000ma. Other than that, most of us who've built our own led rigs, really had to experiment with led counts, color temps, ect... before we were happy with the results. You will probably have to do the same. It's all part of the learning curve and that's what makes DIY so much fun.


----------



## Rockhoe14er (Jan 19, 2011)

I have 12 xpg LED's with 60 degree optics on my 29 gallon tank and they really provide a ton of light. to get 40 par at the substrate i had to raise the lights to about 30 inches above the tank and also rune about .4 amps of current through the LED's. I think you can get away with less LED's or have them run at a lower current. You can check out my thread it's in my signature.


----------



## sink (Jun 11, 2011)

O2surplus said:


> How much current do you plan to run through the XP-G's? I think 12 XP-g's will deliver enough par to grow most plants, if they're driven to at least 1000ma. Other than that, most of us who've built our own led rigs, really had to experiment with led counts, color temps, ect... before we were happy with the results. You will probably have to do the same. It's all part of the learning curve and that's what makes DIY so much fun.


Yep, 1A, the maximum allowed by the drivers. I'm using a modified version of your dual CAT4101 circuit (thank you again!). I didn't see much reason to run them at lower current given that I can just dim them down with PWM if needed.

I don't have plants yet, but was planning on starting with a selection of hardy, fast growing plants and avoiding anything that needs CO2 or high light.

I love the learning aspect of DIY and embrace it . I just don't want to order $75 worth of LEDs only to realize I had overlooked something stupid.

If it was more convenient I would do 6 neutral white, 6 warm white so that I could have fun tinkering with the color, but WW XP-Gs with optics seem very hard to find at good prices and always seem to be in funky bins. Has anybody done a mix using only 12 LEDs and optics? Did the colors blend well enough?


----------



## jcgd (Feb 18, 2004)

Have you checked out the color of NW? It is pretty yellow. WW is pretty much yellow. CW is closest to 6500k ish.


----------



## sink (Jun 11, 2011)

Rockhoe14er said:


> I have 12 xpg LED's with 60 degree optics on my 29 gallon tank and they really provide a ton of light. to get 40 par at the substrate i had to raise the lights to about 30 inches above the tank and also rune about .4 amps of current through the LED's. I think you can get away with less LED's or have them run at a lower current. You can check out my thread it's in my signature.


Thanks for that report--very reassuring. Sounds like I'll have plenty of light output. I've read your thread. Tank looks great! Did you end up using the XR-Es as moonlights or just in series with your XP-Gs? I was going to play with runnign 6 of the LEDs dimmed all the way as moonlights and see how well it works.

Your lights are 30" above the tank, or above the substrate? 30" above the tank sounds pretty cool. Do you have pics of that? 

I thought briefly about dropping to 10 LEDs, but it doesn't really seem worth it, and 12 will provide better coverage. My understanding is also that the difference between 24V and the voltage drop over the LED strings ends up dissipated as heat on the drivers, which don't have much of a heat sink.


----------



## sink (Jun 11, 2011)

justincgdick said:


> Have you checked out the color of NW? It is pretty yellow. WW is pretty much yellow. CW is closest to 6500k ish.


I'm afraid I haven't seen any of them in person. I just know I dislike the "ice cave" look of daylight household CFL lights and suspect I want something warmer than that. IIRC those are 6500k also? I don't know how the XP-G CW lights compare to that, or if some of the ugly is tempered by being inside an aquarium.


----------



## jcgd (Feb 18, 2004)

sink said:


> Thanks for that report--very reassuring. Sounds like I'll have plenty of light output. I've read your thread. Tank looks great! Did you end up using the XR-Es as moonlights or just in series with your XP-Gs? I was going to play with runnign 6 of the LEDs dimmed all the way as moonlights and see how well it works.
> 
> Your lights are 30" above the tank, or above the substrate? 30" above the tank sounds pretty cool. Do you have pics of that?
> 
> I thought briefly about dropping to 10 LEDs, but it doesn't really seem worth it, and 12 will provide better coverage. My understanding is also that the difference between 24V and the voltage drop over the LED strings ends up dissipated as heat on the drivers, which don't have much of a heat sink.


Do you have an adjustable power supply? O2surplus helped me out with those drivers and he told me that you measure the volt drop across the leds and then drop the voltage from your supply down to about 0.5V over what your string drops. That way the drivers don't get so hot.



sink said:


> I'm afraid I haven't seen any of them in person. I just know I dislike the "ice cave" look of daylight household CFL lights and suspect I want something warmer than that. IIRC those are 6500k also? I don't know how the XP-G CW lights compare to that, or if some of the ugly is tempered by being inside an aquarium.


I haven't seen them in person either. I'm using cool white XML in my build but only because they are supposed to be around 5000-8000k or so. I'm also adding some NW and royal blue XPG/XPE to add a way to increase/ decrease the colour temperature.

I don't believe the LEDs have that same gross look as the CFLs. Think of the difference between a T12 florescent and a MH of the same temp. Totally different feels but the same apparent colour.

I'm gunning for a 8000k look myself. I kinda like the bluer, darker ADA look, so that's my goal.


----------



## Hoppy (Dec 24, 2005)

Try using this equation: http://www.plantedtank.net/forums/diy/136733-led-light-36-high-tank-18.html#post1443426 to see what PAR you can expect from your 12 XP-G LEDs. I think it will be much higher than you will want.


----------



## narhay (Feb 28, 2007)

I would suggest 6500K. I enjoy a bluer look but even 6500K is warm-yellow to me.


----------



## sink (Jun 11, 2011)

justincgdick said:


> Do you have an adjustable power supply? O2surplus helped me out with those drivers and he told me that you measure the volt drop across the leds and then drop the voltage from your supply down to about 0.5V over what your string drops. That way the drivers don't get so hot.


That is a good idea. My power supply is theoretically adjustable to +/- 10% of rated voltage but I recall it having a little more range than that when I was testing (albeit with no load).



justincgdick said:


> I don't believe the LEDs have that same gross look as the CFLs. Think of the difference between a T12 florescent and a MH of the same temp. Totally different feels but the same apparent colour.


Hehe. I haven't seen T12 or MH aquarium lights either. But that is a valid point.


----------



## sink (Jun 11, 2011)

Hoppy said:


> Try using this equation: http://www.plantedtank.net/forums/diy/136733-led-light-36-high-tank-18.html#post1443426 to see what PAR you can expect from your 12 XP-G LEDs. I think it will be much higher than you will want.


What a thread. Even fudging some numbers and throwing them into your formula I get a 128 PAR value at a meter away from the array with 60deg optics. I might not be using the formula correctly (that sounds high) but if correct that is *plenty*.


----------



## fishykid1 (Apr 5, 2010)

That's true. If they are not going through water. Light travels much much further and stronger through air than it does in water.


A 400W metal halide bulb will light my whole back yard up like day, but put it in 5 feet of water, and it'll only actively light the top 4-5 feet.

12 XP-G's should be enough light though.

I'm using 12 XP-G's and 8 XP-E (ROYAL BLUE) on a 20G high for a salty tank. I may have to reduce the lighting so it doesn't burn the corals.......it's plenty of light.


----------



## cggorman (May 9, 2009)

I started with 12 neutral whites and felt the color was a bit too yellow, so I added 6 cool whites. I like the 2:1 mix. In my tank it seems like a very natural color. Just for full disclosure, I also run reds and cyans in addition to the whites.

Only half the LEDs have optics. All of those are L'edil Tina2-WW with a 28° FWHM angle. I think that's around a 60° generic optic. This delivers 80-100 PAR (measured)with the fixture about 30" above substrate. All diodes running at max current. Unfortunately, they are NOT Cree diodes so I don't know that translates. The whites are rated at around 200 lumen each and I'm running 18.


----------



## Hoppy (Dec 24, 2005)

fishykid1 said:


> That's true. If they are not going through water. Light travels much much further and stronger through air than it does in water.
> 
> 
> A 400W metal halide bulb will light my whole back yard up like day, but put it in 5 feet of water, and it'll only actively light the top 4-5 feet.
> ...


For all practical purposes light "penetrates" water the same as it "penetrates" air. Very few planted tanks are more than 24 inches deep and practically none are more than 36 inches deep. Only the redder light is affected in a noticeable way by 36 inches of water. In fact, water tends to focus the light rays, so you get a higher PAR than with air. And, the front and back glasses, if kept clean, reflect the light striking them, to increase the PAR even more.

I expected to see that 12 XP-Gs would give you too much light. If you use a dimmable driver, and I think it is essential to do so, getting too much light at maximum power is just right. You can then dim the lights down to the intensity you really want. The LEDs will last forever that way.


----------



## sink (Jun 11, 2011)

cggorman said:


> I started with 12 neutral whites and felt the color was a bit too yellow, so I added 6 cool whites. I like the 2:1 mix. In my tank it seems like a very natural color. Just for full disclosure, I also run reds and cyans in addition to the whites.
> 
> Only half the LEDs have optics. All of those are L'edil Tina2-WW with a 28° FWHM angle. I think that's around a 60° generic optic. This delivers 80-100 PAR (measured)with the fixture about 30" above substrate. All diodes running at max current. Unfortunately, they are NOT Cree diodes so I don't know that translates. The whites are rated at around 200 lumen each and I'm running 18.


Since the response has been so unanimous in favor of neutral white being very yellow, I may end up ordering 6 neutral white & 6 cool white. RapidLED is out of the XP-G neutral whites at the moment anyway so it'll be another week.

For comparison with your emitters, XP-G (R5) nominally put out about 350 lumens at 1A according to the spec sheet.


----------



## sink (Jun 11, 2011)

Hoppy said:


> For all practical purposes light "penetrates" water the same as it "penetrates" air. Very few planted tanks are more than 24 inches deep and practically none are more than 36 inches deep. Only the redder light is affected in a noticeable way by 36 inches of water. In fact, water tends to focus the light rays, so you get a higher PAR than with air. And, the front and back glasses, if kept clean, reflect the light striking them, to increase the PAR even more.


Cool. I'd even expect that the higher above the tank your light is, the greater the fraction of light that reflects off of the glass instead of passing through (due to larger angle of incidence).



Hoppy said:


> I expected to see that 12 XP-Gs would give you too much light. If you use a dimmable driver, and I think it is essential to do so, getting too much light at maximum power is just right. You can then dim the lights down to the intensity you really want. The LEDs will last forever that way.


Yep, I'll be dimming through a PWM signal. I actually was wondering about how that works. I assume the emitter is always operated at a constant current but the emitter is cycled on and off by the dimming signal so fast that our eyes perceive the light as dimmer? I wonder if other species can see the cycling. Maybe we're all driving our shrimp nuts


----------



## Hoppy (Dec 24, 2005)

The dimming signal controls the output current of the LED driver. They don't cycle on and off, they just go to a different constant current.

The higher the light is above the top of the tank, the larger the percentage of the light gets reflected off the glass. You can't paint the back glass without eliminating that reflection, since it comes from the outside glass-air interface, not the inside water to glass interface, but you can use a black or other color panel to give you a background.


----------



## sink (Jun 11, 2011)

Hoppy said:


> The dimming signal controls the output current of the LED driver. They don't cycle on and off, they just go to a different constant current.
> 
> The higher the light is above the top of the tank, the larger the percentage of the light gets reflected off the glass. You can't paint the back glass without eliminating that reflection, since it comes from the outside glass-air interface, not the inside water to glass interface, but you can use a black or other color panel to give you a background.


On my devices the emitter is literally modulated by the PWM signal: It turns on when the pulse signal is "high" and off when the pulse signal is "low". They just do it really fast. See the timing graphs on page 3 of the specs: http://www.onsemi.com/pub/Collateral/CAT4101-D.PDF. I guess integrated drivers work differently.


----------



## redfishsc (Aug 29, 2010)

If you are going with all cool whites and want to save a couple dollars.... and get some of the nicest looking white LEDs out there, try the Bridgelux 402's (10 watters). 

They are reasonably efficient, can be given 65 degree reflectors (they measure them as half angles, look for the 32.5 degree reflectors). 

But they have VERY good color. 

You can get them at Newark or DigiKey.










Here they are at Digikey, $7 each. As good as 2 Cree XPG, so you need half as many.
http://search.digikey.com/scripts/DkSearch/dksus.dll?Detail&name=976-1000-ND


----------



## sink (Jun 11, 2011)

Thanks for the tip about the Bridgelux LEDs -- they look pretty neat. If I were redesigning everything over again I might try them out, but I've already built things taking 2x6 LEDs for spacing and optics into account. Also maximal efficiency is good, as rather than a proper finned heat sink I just have two 28" lengths of 1/8" aluminum L bar, passively cooled for now. See attached photo taken with my ancient flip phone. I think it's a simple and elegant solution. It's not actually a hood--it will be either hung or wall mounted a few feet above tank. With no top or bottom I'm hoping to get enough convection cooling to avoid the need for a fan. But we shall have to see how hot things get.

I went ahead and ordered 6 each of the Neutral White and Cool White XP-Gs with 40 deg optics today. Past the point of no return...


----------



## h2oaggie (Feb 28, 2011)

Cool thread. I am also working on a DIY LED build for a 29, also using 12 XP-G. I went with all cool whites instead, with 40 degree optics, so I am interested in seeing the difference in light output between our fixtures. 

Check out my build thread.


----------



## h2oaggie (Feb 28, 2011)

Here is a diagram a friend made for my fixture. 

This 40 degree optics.
12 inches above tank.
6 LED's per row, 2 rows. Sides are 2.5 in. from tank edge and 5 in. apart.


----------



## O2surplus (Jan 31, 2010)

C'mon lets see that driver. I really want to see what "modified" looks like.:icon_lol:


----------



## sink (Jun 11, 2011)

O2surplus said:


> C'mon lets see that driver. I really want to see what "modified" looks like.:icon_lol:


In this context "modified" is probably best synonymous with "ghetto" :icon_smil

Basically I redrew your board so it's single sided to make the etching easier and added a DS1307 RTC chip and associated circuitry to provide better timekeeping to the Arduino.

I promise I'll provide you some good pictures when complete that you will no doubt find highly amusing.


----------



## sink (Jun 11, 2011)

h2oaggie said:


> Here is a diagram a friend made for my fixture.
> <snip>


Heh, neat. Somebody is enjoying their rendering toys! I guess most of the light intensity is in the middle of the cone so it will be interesting to see how the actual light distribution looks.


----------



## O2surplus (Jan 31, 2010)

sink said:


> In this context "modified" is probably best synonymous with "ghetto" :icon_smil
> 
> Basically I redrew your board so it's single sided to make the etching easier and added a DS1307 RTC chip and associated circuitry to provide better timekeeping to the Arduino.
> 
> I promise I'll provide you some good pictures when complete that you will no doubt find highly amusing.


Can't wait to see them. So you borrowed some power from the 5 volt reg to power the ds1307 and the arduino? That's cool ! It's nice and easy to organize all your wiring that way and avoid purchasing additional power supplies.


----------



## sink (Jun 11, 2011)

Bump!

I finally sat down and learned how to use Eagle. Yesterday I drew out the schematic and then laid out the board, and then printed and etched it today. It came out beautifully, though I did smear the toner transfer on the first attempt (not a problem since I had plenty of spare board). There is definitely an art to routing traces by hand. It is much harder than it looks to make everything route cleanly and avoid a spaghetti mess.

Anyway I finished soldering everything this afternoon and...Holy moly is it bright. The color looks gorgeous--can't wait to see how it looks over the aquarium...whenever I actually set it up. I think the "aquarium" might be just an excuse to conjure up new tinkering projects.

Attached is a [blurry, sorry--I have a lousy camera] photo of the board. Back left is the LM1086 5V regulator, back right are the driver chips, bottom left is the RTC circuit for improved clock functionality. It consists of a DS1307 IC, a coin cell battery, a crystal oscillator, and a few resistors. All resistors and capacitors (and the power LED) are 1206 packages.

There is a minor problem though -- the CAT4101s get hot enough to hit the thermal protection and shut themselves off when run at full power. This happened within a couple of minutes at first. Then I adjusted the power supply down to 20.3V (theoretically 19.8V drop over the LEDs plus 0.5V dropout for the driver) and it improved things a lot but they still run *very* hot. This seems strange. If the supply voltage nearly matches the voltage drop over the circuit there shouldn't be any need to dissipate that heat in the driver, right? What gives? Can I safely adjust down the supply voltage even more?

Anyway I cut a small piece of leftover aluminum L stock and thermal epoxied it across the drivers which should be more than enough heatsink. I'm still curious why I had this problem in the first place, though.


----------



## sink (Jun 11, 2011)

I measured the actual voltage drop over the strings and they are quite a bit lower than I planned for -- one is 18.2V and the other is 18.5V. That is just over 3V per LED instead of the 3.3V listed in the datasheet. This is the cause of my heat issues as I can only adjust the power supply output voltage down to about 20.2V, so each driver has to get rid of nearly 2W -- a lot for a small IC.

Even my makeshift driver heatsink was getting untouchably hot, though the drivers still functioned fine. I added a salvaged computer fan running (albeit slowly) on 5V and the drivers are now merely "warm". Just a heads up -- measure the actual Vf for your LEDs, they might not be faithful to the datasheet.


----------



## sink (Jun 11, 2011)

And just because I'm proud of myself, a photo of the fixture mounted on the wall above the tank! The emitters are 19" above the tank and 37" above the tank bottom glass.


----------



## Ashok (Dec 11, 2006)

Sweet! wish I had the skill to do something like this.


----------



## O2surplus (Jan 31, 2010)

Sink,

I think you need to redesign the driver boards to retain as much copper as possible for cooling the chips. IIRC the chip specs call for 2 square inches of copper per chip. By using the EAGLE software you can retain all the copper you need by designating the top layer of the board a "ground" plane. All you have to do is use the "polygon" command on the top layer and "name" it "GND". This command will only remove enough copper to create a signal traces and leave all the other copper on the board untouched and masked for etching. Send me a PM if you want some help with this, and I'll gladly help you out.


----------



## sink (Jun 11, 2011)

O2surplus said:


> Sink,
> 
> I think you need to redesign the driver boards to retain as much copper as possible for cooling the chips. IIRC the chip specs call for 2 square inches of copper per chip. By using the EAGLE software you can retain all the copper you need by designating the top layer of the board a "ground" plane. All you have to do is use the "polygon" command on the top layer and "name" it "GND". This command will only remove enough copper to create a signal traces and leave all the other copper on the board untouched and masked for etching. Send me a PM if you want some help with this, and I'll gladly help you out.


Argh, missed that in the spec. Thanks, that's a very good point. I don't have much copper on the ground traces at all besides the area directly under the tabs of the drivers. I had tried to add a ground plane with basically the process you describe but wasn't confident that I could transfer the toner accurately enough to avoid shorted traces. Turns out it would have been fine.

Since I'm not confident in my ability to desolder the board without ruining something I'd have to reorder, I worked around the problem with some incremental fixes:

1. Added 2" of 1/8" aluminum L bar thermal epoxied across the drivers, leftover from what I mounted the emitters to.

2. Added a fan pointing at the board.

3. Swapped out the original power supply for a 19V power brick from a long forgotten laptop. This cuts the heat output in half.

I ran the setup at full power for 48 hours straight, and it seems to work fine. The aluminum (both on drivers and emitters) never gets hot enough so that I can't touch it indefinitely. This seems an acceptable situation to me.

Good to know what I did wrong though, thanks! Mistakes are how we learn


----------



## sink (Jun 11, 2011)

Ashok said:


> Sweet! wish I had the skill to do something like this.


Thanks. It's not that bad, really, and fun. As you can see from the thread I learned most of this stuff as I went--and just made up the rest--and it works fine!


----------



## O2surplus (Jan 31, 2010)

sink said:


> Argh, missed that in the spec. Thanks, that's a very good point. I don't have much copper on the ground traces at all besides the area directly under the tabs of the drivers. I had tried to add a ground plane with basically the process you describe but wasn't confident that I could transfer the toner accurately enough to avoid shorted traces. Turns out it would have been fine.
> 
> Since I'm not confident in my ability to desolder the board without ruining something I'd have to reorder, I worked around the problem with some incremental fixes:
> 
> ...


Sounds like you've got the heat issues worked out. I'd let everything be- and just enjoy your handiwork for what it is. Good job!


----------



## sink (Jun 11, 2011)

O2surplus said:


> Sounds like you've got the heat issues worked out. I'd let everything be- and just enjoy your handiwork for what it is. Good job!


Thanks and thanks for your help. Originally your circuits got me thinking about this whole thing in the first place...

I'm traveling for a few weeks (groan, weddings) and then I'll sort out the Arduino+RTC code. Most of the posted code I've seen has been astoundingly bad, and while I'm a lousy electrical engineer, I'm a pretty good programmer. I think I can come up with something much easier to understand and use for setting the RTC and triggering events and then post it here. It should be useful to others.

Then what? Fish. Maybe.


----------



## O2surplus (Jan 31, 2010)

sink said:


> Thanks and thanks for your help. Originally your circuits got me thinking about this whole thing in the first place...
> 
> I'm traveling for a few weeks (groan, weddings) and then I'll sort out the Arduino+RTC code. Most of the posted code I've seen has been astoundingly bad, and while I'm a lousy electrical engineer, I'm a pretty good programmer. I think I can come up with something much easier to understand and use for setting the RTC and triggering events and then post it here. It should be useful to others.
> 
> Then what? Fish. Maybe.



I've got some code that you can use- I don't know how "proper" it is, but it worked well for me when I had an Arduino running my lighting. The code lets you set the time on the Ds1307 and provides "sunrise/sunset" dimming on four channels.
Take a look and let me know what you think.roud:


```
/*
 Arduino Micro-controller (user programmable) LED controller for aquariums.

// micro-processor control of LED lighting systems for aquariums.
// uses a DS1307 Real Time clock to set lighting schedule. Current date and time can be accessed with the serial monitor.
// sunrise/sunset/ length of day selectable programming schedules.  


//  Circuit description
// 
// PWM pins described below connected to dimming circuits on drivers spread among 4 separate channels.
// 
// 
// DS1307 RTC ( real time clock) connected via I2C protocol.
//
//


*/

// Pins to control each channel LEDs. Change these if you're using different pins.
int oneLed = 6;       //Digital pin #6 on the arduino for channel one.
int twoLed = 9;       //Digital pin #9 on the arduino for channel two.  
int threeLed = 10;    //Digital pin #10 on the arduino for channel three. 
int fourLed = 11;     //Digital pin #11 on the arduino for channel four. 

#include <WProgram.h>
#include <DS1307.h> // written by  mattt on the Arduino forum and modified by D. Sjunnesson

// Set up RTC
#include "Wire.h"
#define DS1307_I2C_ADDRESS 0x68

// RTC variables
byte second, rtcMins, oldMins, rtcHrs, oldHrs, dayOfWeek, dayOfMonth, month, year;

// Other variables. These control the behavior of lighting. Change these to customize behavior.
int minCounter = 0;         // counter that resets at midnight. Don't change this.

int oneStartMins = 540;     // minute to start channel 1. Change this to the number of minutes past midnight you want to start
int twoStartMins =540;      // minute to start channel 2. Change this to the number of minutes past midnight you want to start                         
int threeStartMins =540;    // minute to start channel 3. Change this to the number of minutes past midnight you want to start 
int fourStartMins =540;     // minute to start channel 4. Change this to the number of minutes past midnight you want to start 


int onePhotoPeriod = 720;   // photoperiod in minutes, for this channel. Change this to alter the total legnth of the day
int twoPhotoPeriod = 720;   // photoperiod in minutes, for this channel. Change this to alter the total legnth of the day                           
int threePhotoPeriod = 720; // photoperiod in minutes, for this channel. Change this to alter the total legnth of the day
int fourPhotoPeriod = 720;  // photoperiod in minutes, for this channel. Change this to alter the total legnth of the day

int fadeDuration = 60;      // duration of the fade on and off for sunrise and sunset. Change
                            //    this to alter how long the fade lasts.
int oneMax = 255;           // max intensity for this channel. Change if you want to limit max intensity.0 minimum to 255 maximum
int twoMax = 255;           // max intensity for this channel. Change if you want to limit max intensity.0 minimum to 255 maximum 
int threeMax = 255;         // max intensity for this channel. Change if you want to limit max intensity.0 minimum to 255 maximum
int fourMax = 255;          // max intensity for this channel. Change if you want to limit max intensity.0 minimum to 255 maximum

/****** LED Functions ******/
/***************************/
//function to set LED brightness according to time of day
//function has three equal phases - ramp up, hold, and ramp down
void setLed(int mins,    // current time in minutes
            int ledPin,  // pin for this channel of LEDs
            int start,   // start time for this channel of LEDs
            int period,  // photoperiod for this channel of LEDs
            int fade,    // fade duration for this channel of LEDs
            int ledMax   // max value for this channel
            )  {
  if (mins <= start || mins <= mins > start + period)  {
    analogWrite(ledPin, 0);
  }// This is when the led's are off, thus ledVal =0
  if (mins > start && mins <= start + fade)  {
    analogWrite(ledPin, map(mins - start, 0, fade, 0, ledMax));
  }// This is sunrise. Leds slowly brighten to full intensity
    if (mins > start + fade && mins <= start + period - fade)  {
    analogWrite(ledPin, ledMax);
  }//This is when the led's are at maximum intensity
    if (mins > start + period - fade && mins <= start + period)  {
    analogWrite(ledPin, map(mins - start - period + fade, 0, fade, ledMax, 0));
  }// This is sunset. LEDs slowly fade out.
}

/***** RTC Functions *******/
/***************************/
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return ( (val/10*16) + (val%10) );
}

// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return ( (val/16*10) + (val%16) );
}

// 1) Sets the date and time on the ds1307
// 2) Starts the clock
// 3) Sets hour mode to 24 hour clock
// Assumes you're passing in valid numbers.

/*                                         //remove the forward slash and asterisk at the far left to activate the time date setting code


void setDateDs1307(byte second,      // 0-59 
                   byte minute,        // 0-59
                   byte hour,          // 1-23
                   byte dayOfWeek,     // 1-7
                   byte dayOfMonth,    // 1-28/29/30/31
                   byte month,         // 1-12
                   byte year)          // 0-99
{
   Wire.beginTransmission(DS1307_I2C_ADDRESS);
   Wire.send(0);
   Wire.send(decToBcd(second));
   Wire.send(decToBcd(minute));
   Wire.send(decToBcd(hour));
   Wire.send(decToBcd(dayOfWeek));
   Wire.send(decToBcd(dayOfMonth));
   Wire.send(decToBcd(month));
   Wire.send(decToBcd(year));
   Wire.endTransmission();
                                    
}
*/ //remove the forward slash and asterisk at the far left to activate the time date setting code

// Gets the date and time from the ds1307 via the I2C protocol.
void getDateDs1307(byte *second,
          byte *minute,
          byte *hour,
          byte *dayOfWeek,
          byte *dayOfMonth,
          byte *month,
          byte *year)
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.send(0);
  Wire.endTransmission();

  Wire.requestFrom(DS1307_I2C_ADDRESS, 7);

  *second     = bcdToDec(Wire.receive() & 0x7f);
  *minute     = bcdToDec(Wire.receive());
  *hour       = bcdToDec(Wire.receive() & 0x3f);
  *dayOfWeek  = bcdToDec(Wire.receive());
  *dayOfMonth = bcdToDec(Wire.receive());
  *month      = bcdToDec(Wire.receive());
  *year       = bcdToDec(Wire.receive());
}

void setup()  { 
    
// init I2C  
  Serial.begin(9600);
  Wire.begin();
} // these functions only occur once.

/***** Main Loop ***********/
/***************************/
void loop()  { 

 
 
  // get time from RTC and put in hrs and mins variables
  getDateDs1307(&second, &rtcMins, &rtcHrs, &dayOfWeek, &dayOfMonth, &month, &year);
  minCounter = rtcHrs * 60 + rtcMins;
 Serial.print(RTC.get(DS1307_HR,true)); //read the hour and also update all the values by pushing in true
  Serial.print(":");
  Serial.print(RTC.get(DS1307_MIN,false));//read minutes without update (false)
  Serial.print(":");
  Serial.print(RTC.get(DS1307_SEC,false));//read seconds
  Serial.print("      ");                 // some space for a more happy life
  Serial.print(RTC.get(DS1307_MTH,false));//read month
  Serial.print("/");
  Serial.print(RTC.get(DS1307_DATE,false));//read date
  Serial.print("/");
  Serial.print(RTC.get(DS1307_YR,false)); //read year 
  Serial.println();
 
  //set LED values
  setLed(minCounter, oneLed, oneStartMins, onePhotoPeriod, fadeDuration, oneMax);
  setLed(minCounter, twoLed, twoStartMins, twoPhotoPeriod, fadeDuration, twoMax);
  setLed(minCounter, threeLed, threeStartMins, threePhotoPeriod, fadeDuration, threeMax);
  setLed(minCounter, fourLed, fourStartMins, fourPhotoPeriod, fadeDuration, fourMax);
 
  // Get ready for next iteration of loop
  delay(1000);
}
```


----------



## sink (Jun 11, 2011)

O2Surplus:

Thanks! Yes, everybody is using a variant of this code. I'm sure it works fine, I just think it can be made a little bit easier to use.

My main issue is with how ugly setting the time is. You shouldn't have to modify several variables and then uncomment a function in order to update the clock on the RTC. It should just automatically sync the RTC clock to (PC) system clock every time you upload a sketch.

From a few minutes of poking around there may also be nicer ways built into the Wire lib to trigger events.

I won't have time for a few weeks, though. Shame because I'm looking forward to it.


----------



## sink (Jun 11, 2011)

Bump!

I finally got around to digging into the Arduino code and am pretty happy with what I came up with. The result is in this thread.


----------

