Evan Rust
Published © GPL3+

Custom Timer Functions on Arduino Nano

Use the ATmega328P's 8-bit timer and prescaler to implement custom timed events, rather than relying on millis() or delay().

IntermediateFull instructions provided1 hour15,692
Custom Timer Functions on Arduino Nano

Things used in this project

Hardware components

Arduino Nano R3
Arduino Nano R3
×1
LED (generic)
LED (generic)
×1
Breadboard (generic)
Breadboard (generic)
×1
AVR ISP Mkii Programmer
×1

Software apps and online services

Microchip Studio
Microchip Studio

Story

Read more

Schematics

Schematic

Code

main.c

C/C++
#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count = 0;

void hardware_setup(void);

int main(void)
{
	hardware_setup();
	sei();
    while (1) 
    {
		if(count == 100){
			PORTD ^= (1 << PORTD2);		// toggle LED on D2
			count = 0;
		}
    }
}

ISR(TIMER2_COMPA_vect, ISR_NOBLOCK)
{
	count++;
	TIFR2 &= ~(1 << OCF2A);		// lower flag
}

void hardware_setup(void)
{
	CLKPR = (1 << CLKPCE) + (0b111);	// System clk prescaler to 1/128
	DDRD |= (1 << DDD2);	// set pin 2 to output
	TCCR2B = (1 << CS22) + (1 << CS21) + (1 << CS20);	// set to 1/1024 prescaler
	OCR2A = 255;	// output when counter gets to 255
	TIMSK2 = (1 << OCIE2A);		// enable interrupt for match on A
	TCCR2A = (1 << COM2A0);		// also toggle D12
	//ASSR |= (1 << AS2);
}

Credits

Evan Rust

Evan Rust

120 projects • 1053 followers
IoT, web, and embedded systems enthusiast. Contact me for product reviews or custom project requests.

Comments