Arduino “having11” Guy
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 hour2,990
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

Atmel Studio 7
Microchip Technology Atmel Studio 7

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

Arduino “having11” Guy

Arduino “having11” Guy

82 projects • 539 followers
18 year-old IoT and embedded systems enthusiast. Also an intern at Hackster.io who loves working on projects and sharing knowledge.

Comments