Hello folks!
I have started using an attiny10, programmed with the Aduino IDE, for my little LED toggle project. What i have works so far, but i want to expand its functions. This is were i need your help!
- What i have: Attiny10 toggling an LED on/off with the press of a push button.
- What i want: Only toggling the LED on/off after holding down the button a while. If possible, different "holding down" times lead to different actions (think RGB toggle).
- What i've tried (to wrap my head around): Timer0
So, here's my code, hopefully with sufficient comments:
/*
Test setup:
Button Side 1 --> Pin 2 (Ground, GND)
Button Side 2 --> Pin 3 (PB1) --> Internal Pullup Resistor
LED (+) --> 1K resistor --> Pin 1 (PB0)
LED (-) --> Pin 2 (GND)
*/
#define F_CPU 1000000UL //defines CPU frequency, here 1MHZ
#define LED_ON PORTB |= (1 << PB0) //set Bit of only PB0 to 1 (equivalent to DDRB = 0b00000001)
#define LED_OFF PORTB &=~ (1 << PB0) //set Bit of only PB0 to 0 (equivalent to DDRB = 0b00000000) (&=~ equals "unwrite 1")
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
void setup() {
DDRB |= (1 << PB0); //PB0 as output, leaves other bits alone, unlike "DDRB = 0b0001"
DDRB &=~(1 << PB1); //PB1 as input ("unwrite 1"; set to 0)
PUEB |= (1 << PUEB1); //activate internal pull-up resistor for button connected to Pin1
}
//debounce routine for 1 button
bool dbc() {
//set bounce to zero, static retains value after exit
//input on PB1 gets put into bounce
//bounce shifted up by one (<<1)
//new value of PB1 gets into lowest bit
//gets "0ed" with "0xe000" (masking of top 3 unused bits)
//ONLY if bounce = 0xf000, loop returns
//above only happens if input accumulated a 1 followed by 12 zeros
//Summary: tests if lower byte produces a stream of consecutive (12) Zeros --> button contact valid
static uint16_t bounce = 0;
bounce = (bounce<<1) | (PINB & (1<<PINB1)) | 0xe000;
return (bounce == 0xF000);
}
void loop(){
static byte toggle_mem=0; //variable for button press tracking
if (dbc()) {
toggle_mem = !toggle_mem; //invert variable for button press tracking, thus achieving a "toggle" with a push button only
if (toggle_mem) //toogle LED ON when PB1 low
LED_ON;
else { //toggle LED OFF when PB1 high
LED_OFF;
}
while (! (PINB & (1<<PINB1)) ); //If condition "Pin 1 is zero/low" is met, exit loop
}
}
I sincerly hope you can help me and give me some pointers, on how to implenet this my brain is a bit scrambled
Cheers