Digispark: Button
Contents
| Difficulty Level | Beginner |
Note: This documentation is for programming the Digispark with
avr-gccandMakefilesdirectly, not with the Arduino IDE.
Next on our introductory tour of the Digispark ATTINY85 dev board is to accept some digital input, in this case in the form of a button press. Next to flashing an LED, it's about the simplest input that we can accept.
You can find this code in the repo: Digispark ATTINY85 Experiments
The code for this experiment is nearly as simple as for blink:
#include <avr/io.h>
#include <util/delay.h>
// Digispark LED is on Pin 1 for newer versions
#define LED PB1
#define BUTTON PB0
#define DELAY_MS 50
#define HIGH 1
int main(void) {
DDRB |= (1 << LED); // Set pin to output
for (;;) {
int pressed = PINB & (1 << BUTTON); // Check for input on `PB0` -- our button pin
if (pressed == HIGH) {
PORTB |= (1 << LED); // Button Pressed, LED On
} else {
PORTB &= (0 << LED); // Alternatively PORTB &= ~(1 << LED);
}
}
return 0;
}
Explanation
TODO: Explain the code so this is beginner-friendly.
The Makefile is identical to our blink example.
Circuit
For this experiment, we do need to wire up a simple circuit.
Components:
- Digispark ATTINY85
- 1 x LED
- 200 ohm resistor
- 10K ohm resistor
- Momentary button or switch
- Jumper wires and breadboard
Programming
As before, use the Makefile to build and flash:
make
make flash
As a reminder, the command to use micronucleus to upload the hex without using the Makefile:
micronucleus --run main.hex
If everything was successful, pressing the button should turn on the LED until the button is released.
Exercises
Want to explore this experiment further? Try the following exercises:
- Make the LED flash when you press the button and stop flashing when you release it.
- Toggle the LED: one press turns it on, the next turns it off.
- Add another LED in a different color. Pressing the button switches between them. Try different combinations: on/on, on/off, off/on, off/off, blinking.