STAR Firmware by JonnyC - Source Code and Explanation

I’m not terribly happy about it either, but my choices were either voltage-sensitive moon or no moon at all. I did end up bumping up the level a bit though (0/30), so it now ramps from about 3.3 lumens at 4.22V down to somewhere around 0.05 lumens at 3.6V (will have to measure that when I get my battery drained though).

In-between, it spends most of its time in the 0.2 lm to 1.5 lm range, as far as I can tell, which will have to be good enough for now. But I did at least omit moon mode from the low-voltage step-down, since at that point it’s basically the same as “off”.

I considered making it change based on voltage, but the curves are rather non-linear, doing the math on the MCU consumes a lot of space, a table would also consume a lot of space, and it’s not even terribly effective near the bottom end of the voltage range… it still gets extremely dim even with the ceiling set just barely above the floor.

Maybe I could use a small table if I free up some bytes elsewhere, but I’m not sure it matters to me that much.

Yes, I’m using the TOP mechanism. I called it a ceiling. However, I’m not using phase-correct PWM here, it’s fast PWM. The “TOP” thing works in either mode, but phase-correct turns off entirely with PWM=0 and at 1 it’s too bright. I agree that the documentation is particularly convoluted about all this.

FWIW, the cypreus.c firmware got updated quite a bit today. Also, my Ferrero_Rocher/Ramping_UI_table.c firmware makes use of PFM for smoother ramping on the lowest modes, if you’re curious to see another use of PFM.

It’s an interesting concept, but it seems to have very limited usefulness in a flashlight driver.

Awesome, imperceptibly smooth turbo step-down. :slight_smile:

Instead of making the ‘tick’ faster, you could also do something like this:

if ((turbo_ticks > TURBO_LENGTH) && (PWM_LVL > TURBO_STEPDOWN)) {
    PWM_LVL = PWM_LVL - (PWM_LVL >> 5);
}

This way, each step is roughly 3% (small enough to be unnoticeable), and it goes from 255 to 120 in 27 steps (or 13.5 seconds). Should work fine as long as it doesn’t need to drop below PWM=32.

BTW, I discovered today that the WDT is pretty much irrelevant for off-time firmware unless you want to save a tiny amount of power. So, it helps the moon mode run longer but otherwise the power difference is pretty negligible. So, I removed WDT entirely to make room for other code.

Instead I added a non-WDT turbo step-down to my off-time firmware (cypreus.c). It’s not a smooth step-down like yours, but since it’s running on an extremely overdriven host I made it a 2-level step-down. In this case, it’ll drop from ~3000 lumens to ~1400 lumens after 30 seconds, then drop down again to ~500 lumens after another 30 seconds. I should probably make it less than 30 seconds, but that’s what it’s set to now. Hopefully that’s at least enough to keep it from catching on fire.

It’s here if you’re curious:
http://bazaar.launchpad.net/~toykeeper/flashlight-firmware/trunk/view/head:/ToyKeeper/s7/cypreus.c

Dual Mode Change with Single Reverse Clicky

Realized by vex_zg, who thankfully provided the code he used.
Much obliged!

I just want to narrow it down here to the changes he made, to make it easier for anyone who might be interested as well.

What does it do: A short press with the reverse clicky increases the mode, a slightly longer press decreases the mode. It’s like best of both worlds.
Result: Works like a charm.
Verdict: It’s priceless.

I extracted the lines that vex_zg had used and transferred them into a stock StarOfftime1.3. After tweaking the thresholds I get reliable results with short-press and long-press (Toykeeper has even implemented 3 timeframes).
I prefer thresholds 150/100 for now, these make for roughly guesstimated 0-0.5 sec for a short-press and 0.5-1.5 sec for a long-press.

This is with a usual 1yF off-time-cap, no higher capacity required.

So here are the changes.
If the formatting looks odd to you programming aces: I altered it to get a grasp of what this code means, to follow its logic. So it may not be by the book. I don’t know the book. :bigsmile:


Two thresholds instead of single CAP_THRESHOLD

#define CAP_THRESHOLD_SHORT    140
#define CAP_THRESHOLD_LONG    112

Mode change without wrap around. Not necessary for dual mode change, but a nice addition.

inline void next_mode() 
    {
    if  (mode_idx == 0 && mode_dir == -1) { mode_idx = 0; }      
    else    { mode_idx += mode_dir; 
            if (mode_idx > (mode_cnt - 1)) { mode_idx=mode_cnt-1; }         
            }           
    }

Comparing ADCH with the capacitor thresholds. The first and last lines are similar as in OffTime1.3, so it’s easily implemented.

if (ADCH > CAP_THRESHOLD_SHORT) 
        {
        next_mode(); 
        store_mode_idx(mode_idx);
        }
else    
        {
        if (ADCH > CAP_THRESHOLD_LONG) 
        {
        mode_dir=mode_dir*(-1);
        next_mode(); 
        mode_dir=mode_dir*(-1);
        store_mode_idx(mode_idx);
        }        
        else    {
                #ifndef MEMORY
                mode_idx = ((mode_dir == 1) ? 0 : (mode_cnt - 1));
                store_mode_idx(mode_idx);
                #endif
                }               
        }

Again kudos to vex_zg for sharing it.
Have fun.

Yeah, fresh eyes this morning show that I had another crazy interpretation of things. At least I started to put my finger on something I guess… OK, combing through I think I see where WGM00 gets set, that’s when we do TCCR0A=0x21. What I don’t see is where WGM01 gets set. OK, line 453: TCCR0A = FASTPWM; So we are actually in Mode 7, not Mode 5 as I said earlier. WGM00, WGM01, and WGM02 are all set while in Moon mode. In other flashlight modes we are in waveform generation Mode 5 due to setting TCCR0A=0x21. Is that correct?





Changing the subject a little, I think JonnyC wrote this code with a hex value because people could easily increase it by incrementing like a decimal number:

    TCCR0B = 0x01; // pre-scaler for timer (1 => 1, 2 => 8, 3 => 64...)

As far as I know the Waveform Generation Mode isn’t going to work that way. Can we change this:

    TCCR0B = 0x08 | 0x01; // pre-scaler for timer (1 => 1, 2 => 8, 3 => 64...)

To read like this instead:

    TCCR0B = (1 << WGM02) | 0x01; // pre-scaler for timer (1 => 1, 2 => 8, 3 => 64...)

I think that using the register names instead of hex [wherever reasonably feasible] would make the code a tiny bit more accessible. ?

You know, I never got around to looking at vex_zg’s code. Oops. It looks like we wrote almost exactly the same code though. Both offer 3 time frames — short, medium, long. The default STAR off-time uses only two timeframes — short and long.

I still want to tweak the thresholds more… sometimes I have trouble getting a medium press. Otherwise though, it seems to work pretty well. If JonnyC finds it worthwhile he might include it in the default STAR firmware. However, it does complicate the UI and STAR generally tries to “keep it simple, stupid” so it might remain a custom patch.

Yes, I think so. I wanted the blinky modes to actually turn off between blinks, so I made it use phase-correct PWM by default (and only use fast PWM for the always-on modes).

BTW, I tried the idea of changing the ceiling value according to voltage. I had to rearrange a bunch of other code to make room, but I think it’ll work… ish. I’ve only tried a very coarse correction table so far, and due to the variability in voltage measurements, it tends to make moon mode blink brighter or dimmer every few seconds.

This could be fixed by using a bigger table and/or taking an average of several voltage readings, but those both take more space. I’ll probably at least try a slightly bigger table though.

The problem right now is that I’m too sleepy for any complicated math. I’ve got a non-linear curve with an unknown equation (the power to the emitter rising during each pulse) which changes shape according to another non-linear curve (voltage drop), and the only way I can correct it involves another non-linear curve (PFM response curve, roughly 1/x shape). Given these three, I’m trying to make a fourth curve which takes the first three as input and returns a result which is as close to flat as possible. And then quantize that fourth curve into a relatively small table.

That’s too much math for me to do this morning.

I would really love it if this driver had a single 7135 chip available for handling moon mode. (like RMM’s moonlight special, only on a FET driver)

Edit: So, I tried a simpler approach… added a lowpass filter instead. It seems to work pretty well. The PFM level will simply ramp up/down by 1 any time the voltage reading says it’s not right. That means the flicker is very small, and when it does change it’s pretty smooth. If the voltage flips rapidly above and below a threshold, the PFM level will just hang out somewhere in the middle. Plus, it looks cool smoothly ramping up on boot.

OTOH, I’m seriously scraping the bottom of the barrel now for spare bytes. It’s at exactly 1024 and I don’t see anything else I can reduce in size without dropping features.

Oh, yes, probably. But I didn’t know that was a usable symbol in avr-gcc so I used the hex value instead. I think it’s probably fine either way as long as it’s documented / commented.

OK so this totally didn’t compile. Not sure what was going on, sometimes AVR Studio can get confused and compile a nice little nothing instead of what I pasted in there. Also it was pretty late at night. :wink:

This version compiles v004 but does not seem to work correctly. I get around 50% output and no low battery flashes. Does anyone see an obvious reason why?

I think I found a small typo in “MTN_momentary_temp.c”.

// MUX 01 corresponds with PB2, 02 for PB3. Will switch back and forth

0x02 is actually PB4, right?

Is there an off-time version with strobe?

OK, several small changes and this is where I’m at now: v009.c

It’s still definitely not right.

  • I’m able to adjust the output PWM with the pot, but I don’t think I’m getting 100% duty cycle even though the voltage on the input pin is the same as Vcc. (I did not check duty cycle with a scope though).
  • LVP is definitely not working correctly, but so far it has never turned the light off in any version. The best I ever got was around 10 flashes and then 100% duty cycle and unresponsive to the brightness pot. Now….
  • Right now I’ve got some constant pulsing going on, but that wasn’t happening until the latest version… I think.

There are a lot of things I want to tweak, but none of them should be causing these issues… in intermediate versions it felt almost like PB2 was floating, but of course it was not - I checked multiple times with a DMM.

I’m starting to feel like I’m going backwards. I understand better than ever what all this stuff is supposed to be doing, but less than ever why it’s actually doing what it’s doing. It’s all hacked up copy-paste stuff, so maybe significant re-writes would help. In the context of a flashlight where the brightness is controlled by a potentiometer none of the original battery monitoring code makes a ton of sense. I think removing it and starting with a clean slate may be the smart move now.

I guess I’d better disable voltage monitoring again and test to see whether I get full duty cycle with that disabled. Either way the answer is still probably to remove all voltage monitoring code, troubleshoot any remaining problems, then add voltage monitoring back in.

The only one I’ve seen is the one I made in the last couple days… but it’s kind of, um, deviated from its STAR roots. I wrote it to use on my Cypreus, and it’s a tad bit heavy on the blinkies. I haven’t made any which are more appropriate for general purpose use.

I’d suggest copying the strobe bits back into STAR, but the strobe functions are pretty trivial and the code is pretty far from where it started. I suspect my version would only be useful for ideas, not for actual code.

It’s an analog-to-digital signal, converted on cheap hardware, and it’s pretty much guaranteed to be noisy and +/- 10% off spec. It’ll be even noisier if the MCU is doing anything during the conversion. So, it’s safe to assume that you’ll need to scale the values and run a lowpass over them to get any reasonably-sane output.

As for LVP, I think you’re correct that you need to just turn it off until the other functions are working.

Also, it might be helpful to declare all your global variables as volatile. Since the source file isn’t used as a module by other files, declaring globals as static has no effect. Volatile, however, tells the compiler to assume the variable is being changed by other threads or interrupts, and should never be trusted or cached.

I see something else which could be causing issues too…

while(1) {
    if (ADCSRA & (1 << ADIF)) {
        ...
    }
    // Start conversion for next time through
    ADCSRA |= (1 << ADSC);
}

It looks like you’re re-starting the conversion again before it has a chance to finish. The re-start should probably be inside the if, not after it.

You could also just busy-wait on the result, since the code isn’t doing anything else at the time. For example, this is how I block until I get a voltage reading:

uint8_t get_voltage() {
    // Start conversion
    ADCSRA |= (1 << ADSC);
    // Wait for completion
    while (ADCSRA & (1 << ADSC));
    // Return the raw value, caller can decide what to do with it
    return ADCH;
}

I’m not sure if the ADC is as noisy as you think. It’s definitely noisy, but my small experience with MCUs and ADC’s tells me that ADC noise is not the core of any of the actual problems. The driver should behave with no smoothing, it should just be a little rough. I think, heh. I definitely plan to come back and do something about the noise.

Thanks for the poitners on declaring as volatile. I’ve had that explained to me before, but lost track of it. I’ll go through and clean it up.

That final point of yours about the structure of the loop is right on the money. That is clearly a bad setup, I see it now that you have pointed it out. Either blocking for it or moving it inside the if conditional seem equally good to me for this setup. For now I’ve moved it inside the if conditional.

Most recent results:

# With VOLTAGE_MON undefined in v009 the pulsing goes away AND I’m able to turn the output all the way up with my pot. And all the way down.

# No change after moving:

ADCSRA |= (1 << ADSC);

It was still a good point though.

  1. v011 has batt_adc_ticks declared as volatile. It’s the only variable which should be able to change unbeknownst do the main loop. No change.
  2. I went ahead and commented out the entire mechanism that does anything to the output based on voltage monitoring, but left VOLTAGE_MON defined so that the ADC would toggle back and forth. Sure enough, the pulsing is gone - time will tell whether that was ADC noise or a screwup(s) in the LVP section I commented out. In the meantime I noticed that with this setup I still have upper and lower limits on what I can do with the pot. It won’t turn the output all the way down OR all the way up. I’m thinking that I need to do two readings each time I change Vref and discard the first reading.

We’ll come back to that thought though, it’s time to hang up the hat for the day. Thanks for your help ToyKeeper.

To mostly eliminate the noise, it works well to do something like…

  if (ADCH > PWM_LVL) { PWM_LVL ++; }
  else if (ADCH < PWM_LVL) { PWM_LVL --; }

It works pretty well as a lowpass filter, and adds a nice ramp effect when the value changes really quickly.

Or you could, you know, resolve the cause of the noise. But sheesh, who wants to do things properly? :slight_smile:

Yup, thanks! I'll change that comment.

I never added strobe to any of mine. I believe RMM has a strobe option in his versions which I never included back in mine, and of course the other guys here have added their own strobes.

This is what RMM did in the "int main" routine, changed this...

[quote] set_output(modes[mode_idx]); [/quote]

to...

[quote] if (modes[mode_idx] == 254) {

// Strobe. The program will stop here, you will lose the voltage monitoring feature

while (1) {

set_output(255);

_delay_ms(20);

set_output(0);

_delay_ms(60);

}

} else {

set_output(modes[mode_idx]);

} [/quote]

A mode of "254" will become a strobe then. I can add this to STAR and STAR_off_time if it works well enough.

As for strobe, what is the most effective one? Does the 20 ms on and 60 ms off work effectively? Does anyone know if this can be done via PWM by dividing the clock (really slowing down the PWM)?

It’s not necessary to lose voltage monitoring just because the light is in a blinky mode. In mine, I just light up, wait, turn off, wait, then proceed with the main loop (which allows voltage monitoring to happen), then it happens again next time the loop comes around. Instead of using modes[mode_idx] as a code to enter strobe mode, I use mode_idx itself (with #defines to decide how to map indexes to behaviors). The modes[mode_idx] value represents the strobe speed. This way, you can have strobes of different speeds without using mode space in the ROM.

Here is what I’m using, an off-time firmware with strobe modes:

http://bazaar.launchpad.net/~toykeeper/flashlight-firmware/trunk/files/head:/ToyKeeper/cypreus/

That’s the one which has deviated the furthest from STAR though. Its predecessor, ToyKeeper/s7/s7.c, is closer (but is on-time based). Also, they both use party strobes (freezes motion) instead of tactical strobes (for stunning people), so you’d need to change the duty cycle.

From what I’ve heard/read, the most effective tactical strobe is 10Hz with a 50% duty cycle. So, something like this should work:

#define OWN_DELAY
#define SOLID_MODES 4
#define TACTICAL_STROBE_MODES 2+SOLID_MODES
...
const uint8_t modes[] = {
    MODE_LOW, MODE_MED, MODE_HIGH, MODE_TURBO,  // solid modes
    50, 25,  // 10Hz strobe, 20Hz strobe  (1000 / 2 / X == strobe speed)
};
...
int main(void)
{
    ...
    while(1) {
        if(mode_idx < SOLID_MODES) { // Just stay on at a given brightness
            PWM_LVL = modes[mode_idx];
            sleep_mode();  // the WDT will wake us up for voltage checks
        } else if (mode_idx < TACTICAL_STROBE_MODES) { // strobe mode, fixed-speed
            PWM_LVL = 255;
            _delay_ms(modes[mode_idx]);  // requires OWN_DELAY
            PWM_LVL = 0;
            _delay_ms(modes[mode_idx]);
        }
        #ifdef VOLTAGE_MON
        if (ADCSRA & (1 << ADIF)) {  // if a voltage reading is ready
            ...
        }
        #endif
    }
}

As for using PWM to do strobes… it should be possible down to 2Hz (I wrote a script to do the math a while back), but it would require setting the CPU to its absolute slowest clock speed. I haven’t looked up if that can be done from inside the program or if it needs fuses set. So, it might interfere with the PWM on regular modes, and the only real benefit is that it would use slightly less power.

Oops, I just realized/remembered that STAR doesn’t know at compile time how many modes there will be. That certainly makes it harder to use the mode index to decide what kind of behavior to use.

Hi, I really like a feature, rmm’s tk61 super driver has, the momentary turbo from off mode. It works until you leave the long press. Richard gave me some tips on how I can add this to star firmware but my skills dont let me to accomplise that.
Can anyone assist me on that?

Adding momentary turbo from off shouldn’t be terribly difficult, but it has a cost that you lose the ability to map long-press-from-off to something else.

I added it to my todo list, but I’m not sure when it’ll happen.

For now, there are a couple of similar options:

  • Long press from off goes to turbo, release and short-press to turn it off. (in one variant, holding the initial press longer will ramp down) Short press from off goes to the lowest mode (repeat to increase brightness). Turn off by raising or lowering brightness past the maximum level. One version also has a battery check mode on short-then-long-from-off.
  • Long press from off goes to moon, short press goes to last-used level, double click from off goes to turbo. While on, short press turns the light off, long press and hold ramps brightness (smoothly or in steps). Extra-long press from off toggles soft lockout on one version of this UI.

Would either of those work? There’s basically STAR momentary, my version of STAR momentary, a smooth ramping UI, or a stepped ramping UI (like an Olight Baton).