Digispark: Button

Date: 2021-12-19
categories: avr;

Contents

Difficulty LevelBeginner

Note: This documentation is for programming the Digispark with avr-gcc and Makefiles directly, 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:

Fritzing Diagram

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:

  1. Make the LED flash when you press the button and stop flashing when you release it.
  2. Toggle the LED: one press turns it on, the next turns it off.
  3. 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.