Page 2 of 7

Re: Weather Simulation for Dimming expansion module

Posted: Thu Aug 16, 2012 12:47 pm
by rufessor
Just an FYI for anyone considering this, the sunrise and sunset calculations as well as the time handling parts of my code have been adopted by another user who is putting it on the main (no clouds/weather etc) and its working for them using lat lon pairs from yet another place on the globe.

At this point, I am pretty much willing to say that the code works, period. If its not working for you, you did something wrong. Its actually not super hard to do something wrong as it requires a few things... so please post Q's and we will get you working. If your reading this, you know to beware of setups that are externally being given time settings... I myself was unaware that this could/would be an issue... so my recommendation would be to run this off your dimming module UNPLUGGED from the main (unplug the USB mini from the side) and use the USB/pinout cable plugged into the board to load your configured code, then simply LEAVE it plugged into a power up computer and let it run for a day or two until your sure its working..... and it really should be... if its not triple check your LATITUDE and LONGITUDE. It seems like EVERYONE gets this wrong at least one time. Then run it again and see how its going.

It has been run independently by numerous people, code works, so far NO BUGS have been identified for quite some time.

Re: Weather Simulation for Dimming expansion module

Posted: Sat Sep 01, 2012 6:11 am
by rufessor
Ok.... so following up a post saying no bugs have been detected for some time.. with this..... is pretty funny.



I woke this morning to my tank blinking like a strobe. I reloaded software, still doing it, I reset controller, still doing it, I loaded a very simple PWM PDE that just sets lights to steady intensity- thats it... and at least thats working. But... I have no idea whats up- is there something evil about Sept 1 2012 because I cannot even get serial output from my dimming module when I try to load the weather package... so odd... Its been basically perfect but for one (again very recent- like 2 days ago) issue with very low lights on at night, and now its freaking. OUT>

????????????????????????????????

2-3 months of ZERO issues and suddenly it pukes?????

Weather Simulation for Dimming expansion module

Posted: Sat Sep 01, 2012 12:59 pm
by lnevo
When i get some time again Im going to try and compile this in a standalone binary and run it through a loop of date times to see if I can see what's up.

Re: Weather Simulation for Dimming expansion module

Posted: Mon Sep 03, 2012 3:26 pm
by rufessor
that looks to be required at this point. arduino is if nothing else a huge pain in the a.. To troubleshoot. let me know if I can help. I tried to do this once and bailed out as I was in a program with way to many reef angel specific calls but just the date stuff should be revisited. I don't get it at all.... Makes no sense that changing a few 84,600 seconds every day would do anything at all in terms of riseset dying....

Re: Weather Simulation for Dimming expansion module

Posted: Tue Sep 04, 2012 1:32 pm
by lnevo
Ok, I did manage to run the algorithms through as a standalone binary and the output worked great. I did find one bug in my code that I'll discuss in the other thread where I'll specify my corrections, but even looking a few years into the future, the dates all look stable with nothing out of whack. There were some variable casting issues that I had to address which may lead to problems on the arduino that may not be checking as strictly, but I doubt that's getting in the way.... the issue that I had was pretty obvious (I hope that you didn't copy some of mine and introduce the same bug... :) )

Anyway, just wanted to assist in your sanity and the fact that the actual calculations look good. The only big difference now is whether or not to leave that rotation code (but I think we talked about it in the other thread, and I'll leave the discussion there.)

Lee

Re: Weather Simulation for Dimming expansion module

Posted: Wed Sep 05, 2012 9:30 am
by rufessor
Ok... awesome. Using your thread for the port to the main I had a question to ensure I understand how that global declaration was FUBAR the calculation. Once I clarify I will post here the fixed code- If you have tried this code and ran into issues I apologize- but thanks to lnevo helping out and taking an interest we appear to have figured out a very strange behavior.. and it would appear to have arisen through a very unlikely seemingly standard call. Watch here for new code to be loaded and PLEASE try it again if you had issues. It may be a few days but I will be working on this now and get something out ASAP.

My bad- but much THANKS to lnevo! This is what makes open source so awesome!!!!!!!! He stepped in with an interest in what I started and used his skill set to really help out! Very very cool. Thanks again and Congrats! Great things are happening on ReefAngel- no way you get this functionality out of other controllers and this much testing!

My fish miss the storms... so I gotta get this fix done!

Also, have some plans to write in an algorithm that enforces a Minimum day length for those of us using local lat lon but that live in regions with substantial yearly variation in rise and set.... cause my tank is starting to notice the shorter days as we have lost over 1 hour of light all ready. This will be invisible to the end user but for the addition (I think... just planning this) of a single variable specifying the minimum desired day length (probably in total seconds). I think I will just distribute the day extension equally so that the tank rises and sets earlier/later by 1/2 of the total difference in actual v.s. minimum day length. Didn't know I would need this, but its becoming apparent that I/we (depending on your Lat/Lon choice) probably do.

Re: Weather Simulation for Dimming expansion module

Posted: Wed Sep 05, 2012 9:50 am
by lnevo
rufessor, not sure if the issue I had was the same as what you experienced...unless you copied something from my code. I'll post the explanation on the other thread in a moment what was going on...

Re: Weather Simulation for Dimming expansion module

Posted: Thu Sep 06, 2012 1:17 pm
by rufessor
Negative on that... unsure why my dimming module went whacky.

Re loading current working code to see if it was just a random thing. The error you found was indeed specific to how you had coded in the Lat/Lon conversion and could have produced exactly what you found, because on the second calculation run through you would have basically been using some mythical location with a very very large number... Your fix seems to be working, congrats on figuring that out. I had not gone through it step by step like a processor would so I missed that it would calculate the conversion using the prior result of that calculation. They way I originally coded it does not do that... and thus there is no apparent reason for it to have freaked out.

For those interested, I will update here when I reinstall and see what happens. I guess its just possible that after 2 months continuous running the processor simply finally lost track of memory and I need to do a complete reload of the code, and a good power off (for a minute or something) cycle to truly clear all memory etc. If thats all it takes and I am up and running, then I am just going to chalk this up to random crap, especially now that the Lat Lon code has been validated completely independently of my saying its working just fine.

Sorry for the confusion, I initially had read the error report thinking he had caught something in my code when he ported it, but it was an introduced error and is NOT part of the code attached to this thread. Which is nice- since I thought it was OK.

I guess were back to square one, the code should work for you, post here if its not.

I will reinstall on my own module and get it up and running using the actual code from this thread as a further test since I want to re-load anyhow.

Weather Simulation for Dimming expansion module

Posted: Thu Sep 06, 2012 4:44 pm
by lnevo
Why not leave your code and pick a location closer to equator and more conducive to corals rather than mess with your already good functions :)

Re: Weather Simulation for Dimming expansion module

Posted: Sun Sep 16, 2012 8:52 am
by rufessor
I like having real sunrise and sunset but the short winter kinda requires zi think either editing of the choffset array, which is how I am running it now, but it is super easy to justdistributethe minimum day length so I will add it and make it so if you enter a zero it's ignored.

I am tying it on my system but my pmw board clock is now wrong, never has been before so this must have caused it. Gotta figure out how to set it without main working....

Re: Weather Simulation for Dimming expansion module

Posted: Wed Sep 26, 2012 9:23 am
by rufessor
Sooooo..... I figured out why my dimming module suddenly went crap-0-la and stopped working.

Damn fish :twisted:

I recently added a Niger (red-tooth) trigger to my tank. It is doing very well, eats like a pig and also apparently enjoys surfing the stream coming out of one of my power heads up near the back left corner (top) of my tank, which is- you guessed it- right over my dimming module sitting down near the ground. :o

Summary and basic electronics tutorial.

Corals and trigger fish live in salt water.
Salt water is apparently corrosive to PCB circuitry (who'd a thunk :mrgreen: )
Short circuiting PCB circuitry causes massive issues with actually running a program
I need a new dimming module

So- PLEASE... if your like me and were loading a ton of stuff to a dimming module during development, then got it all working and had it running for a few months but were too lazy to screw on the nice plastic case to keep the water off it... well... you might consider doing that ASAP. Its mUCH cheaper.

Re: Weather Simulation for Dimming expansion module

Posted: Thu Oct 25, 2012 7:08 am
by Soehl
I have a MP40w and a MP60w running on my tank. Would it be that difficult to work them into the code?

I am a complete newb and get frustrated(and scared) faster than I can learn this stuff. lol

Re: Weather Simulation for Dimming expansion module

Posted: Wed Nov 14, 2012 9:16 am
by rufessor
Sorry for the long delay... since my module was fried by the damn fish I have been using the very sophisticated method of plug the lights in in the morning and un-plug them at night... it almost exactly mirrors my awake time :)

But... my new module will be here this week so I can play more. The code running on the dimming module really is isolated from the pump. However, and I keep saying I am going to do this.... it is pretty easy to get the dimming module to talk to the main and tell it its a storm, cloud, sunny etc which then could be used to change pump settings. However, although I may put up something with comm in it, I do not have programmable in tank pumps/power heads so I would not be able to help you. That said, there all ready exist a number of implementations for the pumps you have and it would be trivial to change a few lines to get them to run based upon the storm/cloud/etc output from this program.


Just to reiterate for everyone else looking here... the code for the weather package is working 100% and some of it has been ported to the main by lenovo. The only reason I was worried about bugs was the unknown fact that my fish was slowly killing my dimming module... ;

Re: Weather Simulation for Dimming expansion module

Posted: Tue Nov 20, 2012 9:14 am
by rufessor
So here is a bit of code that might be one solution to the short winter days, and to fixing the bleaching I was getting due to the 17 hour summer days... first bit can be used to symmetrically shift the day to a longer time by just using set=set(5e-1*etc... for each line...

Second bit is not going to work currently due to issues with ChOffset needing to be defined here so its not continually edited downward.... and I am not filling it correctly, I just copy and pasted so ignore that array statement stuff but once I get that fixed the for loop should do what we need... it indexes intensity down as a decimal percentage of the length of the extra daylight (beyond desired light on time) as compared to the desired day... so if your desired day is 100 seconds and your sun rise and set yield 110 your extra day light is 10 seconds, which is 10% of 100 so your lights would be set to 0.9*ChMax values... hope that makes sense...

This is just to gather comment, the first part would probably run now, the second is a SKETCH... with known bugs and issues, it will not even compile.. just thinking this through a bit.

if ((set-rise)<45000){
long dayDelta;
dayDelta=45000-(set-rise);
//change following constants to sum to 1.0 to distribute additional seconds of day accordingly
set=set+(7e-1*dayDelta);
rise=rise-(3e-1*dayDelta);
}
if ((set-rise)>45000){
float dayDelta;
dayDelta=(set-rise)-45000;
dayDelta=1-(dayDelta/45000);//as fractional decrease in intensity max setting for the day (every 10% longer than 12.5 hours reduces ChMax to 0.9*ChMax)

//adjust intensity to compensate for long days
for (byte b=0; b<8; b++){
ChMax=ChMax*dayDelta;
}
}

Re: Weather Simulation for Dimming expansion module

Posted: Tue Dec 11, 2012 1:36 pm
by rufessor
Ok... so I have code compiled that I will be uploading.

What I noticed is that as the seasons changed I got better coloration in my corals, which has now transitioned into some of the Zoas that are partially shaded have begun growing long necks "reaching for the light" so I know that given my latitude and longitude I have too much PAR variation throughout the year, with peak summer causing some loss of coloration even slight bleaching and the depths of winter causing light stress due to too little light.

I decided to take a two pronged approach. Since you cannot go higher than full PWM 100% output which is constrained by the dimmer at whatever max current output you set, the only way to fix the winter light shortage is to enforce a longer day. Since I like to view my tank at night and with sunset before 5 pm where I live, the tank is going dark before I get a chance to fully enjoy it so my solution to adding time to winter days is to basically set a minimal daylight period of 12.5 hours. Then when days are less than that, add back the required time to get to 12.5 hours (45000) seconds and distribute it asymmetrically such that the sunset is delayed more than the rise is accelerated.

Then, if the day is longer than 45000 seconds I decided to use PWM dimming to REDUCE the channel intensity set points by the fractional day length difference

e.g. if the day is 49500 long, which is 4500 longer than 45000 seconds (10%) the individual channel intensities are set back by 10% of their value (in the last part of the code which is from insolation). I am using integer math to do fractions so I am calculating the percent difference and adding 100 to it... if that helps make sense.. this is stripped out in the last bit.


First - you need to globally initialize a variable so add this to the setup

float fracInt;

Then... this code goes into CalSun right below the final calculations to rise and set for elapsed day time.

Code: Select all

//Minimum desired day length is inside if statement 45000=12.5 hrs
 //calculation distributes additional time required to yield 12.5 hour light cycle symetrically to rise and set if you use 5e-1 as constant in if loop below
   if ((set-rise)<45000){
     long dayDelta;
     dayDelta=45000-(set-rise);
     //change following constants to sum to 1.0 to distribute additional seconds of day accordingly
     set=set+(75e-2*dayDelta);//75% of the additional time is used to delay set
     rise=rise-(25e-2*dayDelta);//25% of the additional time is used to set rise to earlier value
     fracInt=100;//set this to make no correction to intensity in insolation for short days
   }
   //Max desired day length at 54000 is 15 hours
   //If calc day length exceeds trim to 54000 and set rise to 0.7 of difference (adding 0.7 of excess) with the rest coming off set 
 else if ((set-rise)>45000){
     float dayDelta;
     dayDelta=100*(((set-rise)-45000)/45000);
     //change following constants to sum to 1.0 to distribute additional seconds of day accordingly
     fracInt=dayDelta+100;//fractional math with integers requires scaling to remove decimal
   }  
 else fracInt=100;//set this for days that are exactly equal to 45000
Then, I changed the Insolation routine a little bit so that once the actual fractional intensity required at the given point of the day (modeling solar insolation using a cosine) the actual output light setting is modified by the fracIntensity to downgrade intensity set point on long days to avoid bleaching.

To assist in not having to find the small changes I made throughout this routine, I am just copy pasting the entire function.

Code: Select all

void Insolation()
{
  InsolationAdvance=false;//reset this flag now that we have entered function

        //define Pi as delta Y for slope since cos 0.5-1.5 Pi goes 0-1-0 in 0.5 pI increments slope of 1/2 day (0-1 intensity) delta Y is 1/2 Pi 
        float Pi=3.1415926;//scale to 10^8
        float PiHalf=1.5707963;//scale to 10^8
        
        float secSoFar;//variable to account for seconds elapsed for each channel 1/2 day period from rise-->midDay and midDay-->set
        
        /* using -cos(pi/2+elapsedTime/slope) calculate fractional intensity of each channel throughout the day
         use flicker points to adjust minimum intensity to stable light.  Turn off lights after set or before rise etc.
         by splitting into half days centered on midday (1/2 ofset-rise) we center exactly the cos function for every channel so color blends are maintained 
         throughout intensity ramp... more or less ... change intensity every 120 seconds throughout the day*/
         if (elapsedTime<=midDay){
           byte c=0;//loop counter
            for (byte b=0;b<16;b=(b+2)){
                if (elapsedTime>=ChRiseSet[b]){
                    secSoFar=(elapsedTime-ChRiseSet[b]);//just account for length of every channel 1/2 day and switch at midDay
                    ChannelValue[c]=ChMax[c]*(-cos(PiHalf+(ChSlope[b]*secSoFar)));
                 }
                 else if (elapsedTime<ChRiseSet[b]){
                   if (MoonCh[c]==1){  
                      byte MoonToday=MoonPhase()*0.5;//SCALE FACTOR to DIM moon setting for use with HIGH power LED as moon light
                      if (MoonToday==0) ChannelValue[c]=0;
                      else ChannelValue[c]=MoonToday;
                   }
                   else if (MoonCh[c]==0){
                     ChannelValue[c]=0;//its dark and this is not a moon phase channel
                   }
                 }
              c++;//index by one so we count 0-7 as b goes 0-14 by twos
            }
        }  
        else if (elapsedTime>midDay){
            byte c=0;//loop counter
            for (byte b=1;b<16;b=b+2){
              if (elapsedTime<=ChRiseSet[b]){
                    secSoFar=(elapsedTime-midDay);
                    ChannelValue[c]=ChMax[c]*(-cos(Pi+(ChSlope[b]*secSoFar)));          
               }
               else if (elapsedTime>ChRiseSet[b]){
                   if (MoonCh[c]==1){  
                      byte MoonToday=MoonPhase()*0.5;//SCALE FACTOR to DIM moon setting for use with HIGH power LED as moon light
                      if (MoonToday==0) ChannelValue[c]=0;
                      else ChannelValue[c]=MoonToday;
                   }
                   else if (MoonCh[c]==0){
                     ChannelValue[c]=0;//its dark and this is not a moon phase channel
                   }
                }
              c++;//index to count 0-7 as b counts 1-15 by twos.
            }
        }  
     //The next bit modifies the actual ouput intensity to account for day length variations in attempt to maintain PAR levels 
     //throughout the year.
     //You must set ChMax to obtain adequate PAR for a 12.5 hr (45000) light day
     //This modifies that by REDUCING indensity linearly by % day length over 12.5 Hr for any day over 12.5 Hr.
     //Add Flicker setting to all utilized channels (ChannelValue!=0) to avoid flicker
     byte a=0;
     for (a=0;a<8;a++){
       if (ChannelValue[a]!=0){
         ChannelValue[a]=((ChannelValue[a]/fracInt)*100)+flicker[a];
       }
     }  
   }//END function
//WEATHER FUNCTION BEGIN
The rational i use for taking a direct percent of daylength to modify PWM setting is that the PAR value is "set" at 100% of whatever that is with a PMW setting of 255. Using PWM dimming you are NOT altering the intensity of the LED by modifying current, you are simply flashing it at 100% current- very quickly. So, if you simply flash it 10% less you aught to deliver 10% less PAR to the tank... we shall see.. but it will literally take nearly a year to tell if this is a fix as there is no way to assess this in terms of coral coloration and growth other than to watch the tank.

I AM NOT CERTAIN THAT THIS IS A GOOD APPROACH for analog dimming... maybe someone can chime in.

Re: Weather Simulation for Dimming expansion module

Posted: Wed Dec 12, 2012 10:45 am
by rufessor
I have the mods running and all the code for expanding the daylight times if the day is less than 12.5 hours is working correctly. So if you want this, go ahead and use it. As for the code to dim according to % day length exceeding 45000 seconds- I am not planning on really testing this until summer rolls around and then only will have any idea if its working after we get well into summer and I can see if the corals avoid the bleaching I was seeing- although I suspect it will fix the problem its going to be a months long process to determine if its an adequate adjustment... so when we roll though July I will post back how things are working.

Re: Weather Simulation for Dimming expansion module

Posted: Thu Mar 14, 2013 12:13 am
by EOD80904
So I figured out what to change within the sketch to use with a mega.I also added some code to the loop to see each channel intensity in 0-100%.

Code: Select all

for (int i = 0; i < 8; i++) {  
        Serial.print(" ");
      if (ChannelValue[i] < 10)
        Serial.print(" ");
      else if (ChannelValue[i] < 100)
        Serial.print(" ");
        Serial.print(map(ChannelValue[i], 0, 255, 0, 100));
        Serial.print(" ");
      }

Re: Weather Simulation for Dimming expansion module

Posted: Mon Mar 25, 2013 4:58 pm
by cgaubuchon
So my (first) question is why did you go the route of making this a PWM expansion from the start?It seems like in doing so you automatically limit or make things more difficult to communicate with the Portal and the Controller.

Being somewhat new to RA but well seasoned with Arduino I may be missing the reason but it seems like the code could pretty easier just as well work if flashed to the controller instead.

Just curious as taking apart the PWM to flash changes seems like an extra step without any real benefit other than maybe saving memory space on the controller.

Thanks!

Weather Simulation for Dimming expansion module

Posted: Mon Mar 25, 2013 5:17 pm
by lnevo
I think it was initially a memory decision. This code may even be out pre ra+ the independent sunrise/sunset class can be used on the main unit and this code could probably be easily ported for the main unit as well.

Re: Weather Simulation for Dimming expansion module

Posted: Fri Mar 29, 2013 11:00 am
by rufessor
This was indeed created pre RA+ and was specifically coded on the PMW expansion module as the older (and many are still current use) RA controllers were pretty constrained with respect to memory and thus to enable full use of the controller I wrote it to be run on the PMW board since it of course has a processor equivalent to the original RA. I am actually going through this code and restructuring it into compact subs so that it can be more easily incorporated into the library and would then be available to all users regardless of configuration so long as memory was in fact free.


I should also note that there is an error in the code in two places, my recently posted update to allow for PWM intensity alteration during extended photo periods during the summer months has a simple error in the math which I have now corrected. I also found an error in the cloud period calculation that is invisible to the user but results in some differences in length of cloud period throughout the days from what I had intended. I will be posting the new package with compact subs relatively soon. My coding skills have moved significantly as I have been working very intensively on PERL for my job and thus I anticipate that I will likely make wholesale changes to the code base since this code evolved as I in fact taught my self the version of C that arduino makes use of and as anyone who has spent any significant time coding will tell you.... your first efforts, although functional, begin to look pretty darn ugly as you learn.

The reason I have not pushed to get this into the library is that the code is very difficult to maintain currently as some subs are pages long which is a cardinal sin- thus I am repenting for my sins and re-doing his in my limited spare time.

I have also made some more changes to the clouds allowing for random drift to occur between the different colors available so that during clouds the actual color temperature of the tank changes. I had initially thought this would look stupid but I tried it and find that it in-fact is a subtle but noticeable improvement as it adds additional variety.

If your using this code with the day length mods for summer and winter as I posted above your probably keeping up with this and would not mind making the simple changes to the lines I have corrected so if you PM me I can send you the changes to make. If your thinking about using it... maybe give me a week or two to get it reworked and tested then I will see if Kurt has time and interest to incorporate this into the library so all can use it.

The other reason I have not gone so far as to ask for it to be put into the library, is that making changes then becomes a much different task as they would be needed to be pushed into the current implementation of the library and then become part of an update and until I am happy with it being maintainable, error free, and truly worthy of incorporation I was hesitant to push for it being in the library.

I promise to get this out. I had been thinking that very few people were using it and just playing with it on my own but have been made to believe that perhaps there is a wider audience and thus will do my part to ensure that once its "out of my hands" and put into the library, its as good as I can make it and easier to understand.

Re: Weather Simulation for Dimming expansion module

Posted: Fri Mar 29, 2013 11:02 am
by rufessor
Got it significantly cleaned up... will be testing soon

Re: Weather Simulation for Dimming expansion module

Posted: Wed Apr 03, 2013 2:37 pm
by rufessor
Question-

Can I use structures or is this going to cause problems in porting this into the library?

Thinking of creating a structure (basically a class) to hold the diverse globals I use then I can pass that around to modify individual components in subroutines. But... it requires a .h file to be linked which contains the structure declaration and I am not sure if this will munge things up later.

I should also admit I am not certain I am going to do this... but it looks to be a nice compact way to hold globals allowing almost a hash like database... enabling me to rapidly add a "global" variable when I need by simply assigning a new member to the structure. In some ways it seems like this would in fact be better for incorporation into a code library as it "isolates" my stuff from everything else. But I will have to change a lot more of the code so I am not going here until I can figure out if its supported or advised.
Kurt? or Roberto? others who know?? thoughts?

I am likely exposing my ignorance here... cause its probably obvious- but only if you know it :)

Weather Simulation for Dimming expansion module

Posted: Wed Apr 03, 2013 3:20 pm
by lnevo
My moon simulation uses a struct but a related code was stuck in the .h file also the sunlocation and tide classes that you have to add to the libraries. So anyway you choose to go.

Re: Weather Simulation for Dimming expansion module

Posted: Wed Apr 03, 2013 3:55 pm
by rufessor
Sent you a PM... but to include others.

If I make a big structure to hold the necessary globals we now have a new .h file - seemingly not a big deal just one include line in the main. But, then any edits to the program for say, inclusion of a new variable or something require the .h file also be edited or (seemingly not a good choice) a new struct be created that inherits the old and includes the new elements. This gets nasty fast so I am not proposing that but am I missing anything with the idea of using a structure to hold all the globals.

Thinking I can then just initialize them as type and bounds within the structure and then in the code simply fill them as they are created. Seems like a good way of avoiding collision between variable names and its no big deal to simply edit the .h file containing the structure if we need a new variable. But I am not seeing this as saving many lines of code... just not sure I should through to the effort.

Proposing something like this


new .h file...

typedef struct{
long rise;
long set;
byte ChMAX[8];
etc...
}Weather


Then in code...
include Weather.h

Weather.rise=sunriseFunc(timenow);
and another example...
Weather.ChMAX[0] = calculation result for that channel intensity;

But this of course means that I need to go through every line of code and for all variables switch to the structure format ..

e.g. rise now becomes Weather.rise etc etc so is it worth the effort for name space preservation?

Weather Simulation for Dimming expansion module

Posted: Wed Apr 03, 2013 4:18 pm
by lnevo
I think you can just define the struct in the main ino file. You only need a separate declaration file if your going to share between other c files. I believe...

Are you planning to have seperate c files or put all the code into the .h file?

Re: Weather Simulation for Dimming expansion module

Posted: Thu Apr 04, 2013 11:24 am
by rufessor
Having not yet done this, I can only say that there are numerous posts on Arduino forums stating that the compiler has issues with package creation occurring in what amounts to an inappropriate order for it to be included in with the code so the recommendations there for simplest fix is just to use an external file and include it. Thus that was going to be my method of choice (its not like I can't then test this by copy and paste so whichever works I guess). In terms of going to a full object oriented implementation, that would probably in this case be more work than required and do little other than split it up over a bunch of files and objects. If it was going to be a core implementation that would spit out stuff like rise and set and cloud times and storm stuff across a widely dispersed set of implementations it might be worth it but since its running on the controller and is basically designed to be a compact package its kinda not worth it IMHO.

Re: Weather Simulation for Dimming expansion module

Posted: Sat Apr 06, 2013 6:24 am
by binder
Just to chime in. Structures and classes are virtually the same. A structure is simply a class without functions (yes, I'm paraphrasing it).

If you plan on only using the variables in one file (Weather.cpp), then you won't need to have a header file. You can simply put all the variables at the top of the file (like you are already doing).
Ideally, you would have a header file and an implementation file for all the functions and you would turn it into a class to keep everything grouped together nicely. Then the class would only use the variables that are associated with it. This would make things simpler to deal with.

If you were to put all of your functions into a separate file and then create the variables in the sketch, you would run into problems like you were discussing. The compiler will not be able to locate the variables for use with your functions because they are located elsewhere. This is why a header file is needed. (which I'm sure you already knew that).

You mentioned that it could get "nasty fast" by having to include lots of variables in the header file. I would think that if you created the functions properly, there really wouldn't be a need to continually edit the header file with the variables. If you have to modify values, the best route would be to create a class and then have functions to initialize the variables and update them as needed for use in the code.
If you have to create more variables and functions in the code, then that's just how it goes. Having them located in 1 or 2 files and separate from the other code is much easier to deal with. Then you just have a class to included and start using.

With a class, you could simply have 1 function call to calculate all the values and store them in the proper variables and then have a function call to return the values.

IMO, have the class would be the best solution because of consolidation and isolation of the code and maintaining simplicity.

Going off of your example, here's a way it could potentially be used:

Code: Select all

class Weather {

public:
	Weather();

	// updates the values
	// calls CalculateSunrise, CalculateSunset, CalculateIntensity
	void Update();
	long GetSunrise();
	long GetSunset();
	byte GetIntensity(int channel);

private:
	// calculates sunrise and stores it in rise
	void CalculateSunrise();
	// calculates sunset and stores it in set
	void CalculateSunset();
	// calculates the intensity for channels and stores in ChMax
	void CalculateIntensity();

private:
	long rise;
	long set;
	byte ChMax[8];
};
Inside your INO file, you include "Weather.h"
Then have a global Weather variable:
Weather w;

Inside your loop you would have something like this:

Code: Select all

void loop() {
	// code
	// or have code that only updates 1 time per day
	w.Update();
	// this is not the proper format, just an example
	PWMSlope(w.GetSunrise(), w.GetSunset());
	// code
}
You could even use it inside the DrawCustomMain() function.
This way you don't have to worry about creating all the variables you need, you can simply keep them isolated and have a common interface to be used just like the rest of the libraries.

Just throwing out some ideas for you. Personally, I think the class is more readable, but that's just my opinion.

Re: Weather Simulation for Dimming expansion module

Posted: Wed Apr 10, 2013 12:35 pm
by rufessor
Thanks Kurt-

Class structured (OO whatever) C++ is not something I have done before but I am using Object Oriented structure in Perl for work so its not really foreign. Let me make something up that I think will mostly work out and have you take a look at it via PM. This is going to take a little longer cause the coding part of my brain is currently being completely fried by projects at work... so I need to finish a few things to free up some time to play!

Thanks- PM will eventually show up

Re: Weather Simulation for Dimming expansion module

Posted: Wed Apr 10, 2013 3:13 pm
by binder
rufessor wrote:Thanks Kurt-

Class structured (OO whatever) C++ is not something I have done before but I am using Object Oriented structure in Perl for work so its not really foreign. Let me make something up that I think will mostly work out and have you take a look at it via PM. This is going to take a little longer cause the coding part of my brain is currently being completely fried by projects at work... so I need to finish a few things to free up some time to play!

Thanks- PM will eventually show up
haha. Yeah, I can COMPLETELY understand about your brain being fried. Mine gets that way too from work and play.

Re: Weather Simulation for Dimming expansion module

Posted: Fri May 10, 2013 8:53 am
by rufessor
ALmost there at least in terms of a first try at this... probably much will be obviously a bit wrong in the implementation...


Lenovo and Kurt- I will PM you with some code- if you do not mind can you just LOOK at it. I have not tested it I just want to know if I have the structure correct.

I took your advice and tried this as a class... it will be much more portable that way. But this is my first and only attempt at this in C... its different than Perl so its likely I have things just a bit stupid..


Don't worry about doing any debugging or compile just need to know if it looks right for this. Your help will greatly speed my getting this done. Working off examples only takes you so far...