This is how I trigger brightness on my POVpoi unit. It’s using an ATmega32U4, but the same principle applies to a Tiny85 (which has two interrupts versus the 32U4’s five.) First the interrupt is set in the setup() portion, I’m using interrupt 4, and the button is configured as an active-high:
void setup() {
attachInterrupt(4, intHandler, RISING);
// other setup stuff
}
Then, the interrupt handler itself which in my case I named ‘intHandler’ - you can call it whatever you want as long as the function also has the same name:
void intHandler() {
// Interrupt for brightness button
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
// deBounce the button!
if (interrupt_time - last_interrupt_time > 200) {
brightness();
last_interrupt_time = interrupt_time;
}
}
Note the button debounce! This is important, otherwise you will register false triggers very easily. I’m doing a 200ms debounce which works great.
Note that I’m calling a function called ‘brightness’. This is because an interrupt handler needs to be as short and quick as possible. It can not have (or should not have) any large code and certainly no delay() in it. So if you take away all the debounce lines, all you’re left with is the single call to the brightness() function.
The brightness() function itself looks like this:
void brightness() {
brightnessLevel++;
if (brightnessLevel > 6) brightnessLevel = 1;
switch (brightnessLevel) {
case 1: LEDS.setBrightness(64); break; // 25% - default
case 2: LEDS.setBrightness(128); break; // 50%
case 3: LEDS.setBrightness(255); break; // 100%
case 4: LEDS.setBrightness(8); break; // 3%
case 5: LEDS.setBrightness(16); break; // 6%
case 6: LEDS.setBrightness(32); break; // 12%
}
}
So by default, I start at 25% (this is set in the main setup(0 section) and subsequent clicks will increase towards 100% then loop back to the lowest setting. I keep a single variable, brightnessLevel, that the case statement then checks. Every time the brightness() function is called, it increases the variable. When it reaches max (6), it loops back to 1 which is the lowest setting.
The advantage of doing it this way is that I don’t have to constantly be calling the brightness nor interrupt handler while the main loop() is running. It only gets called whenever the button is pressed and the interrupt triggered.
Hopefully this helps.