Snippets

Yuri Tachometer for AVR ATTiny2313 (from 2010)

Created by George T.
#include <avr/IO.h>
#include <util/delay.h>
#include <avr/interrupt.h>

char com;
char oct;
unsigned int TM = 0;
unsigned long AN = 0;
unsigned int last = 0;
unsigned char cht = 0;

ISR(TIMER1_CAPT_vect)
{
	unsigned int time;
	time = TCNT1;
	cht++;
	if (cht%2 != 0)
		last = time;
	else
		TM = time - last;
}

void lcd(unsigned int p)
{
	_delay_ms(1);

	if (com == 1)
		PORTB &= ~_BV(PB0);
	else
		PORTB |= _BV(PB0);

	unsigned int PH,PL;
	PH = p / 16;
	PL = p % 16;

	PORTB |= _BV(PB2);
	PORTD = PH;
	_delay_ms(1);
	PORTB &= ~_BV(PB2);

	if (oct == 1)
	{
		_delay_ms(1);
		PORTB |= _BV(PB2);
		PORTD = PL;
		_delay_ms(1);
		PORTB &= ~_BV(PB2);
	}
	_delay_ms(1);
}

void lcd_init(void)
{
	com = 1;
	oct = 0;
	lcd(0x30); _delay_ms(5);
	lcd(0x30); _delay_ms(5);
	lcd(0x30); _delay_ms(5);
	lcd(0x28); _delay_ms(5);
	oct = 1;
	lcd(0x28); _delay_ms(5);
	lcd(0x08); _delay_ms(5);
	lcd(0x01); _delay_ms(5);
	lcd(0x06); _delay_ms(5);
	lcd(0x0C); _delay_ms(5);
}

void lcd_clear(void)
{
	com = 1;
	lcd(0x01); _delay_ms(2);
	lcd(0x06);
}

void lcd_text(char *str)
{
	com = 0;
	unsigned int len = strlen(str);
	for (int i=0; i<12; i++)
	lcd(str[i]);
}


void lcd_num(unsigned long int a)
{
	unsigned long int b = 0, c = a;
	while (a > 0)
	{
		b = b*10 + (a%10);
		a /= 10;
	}
	com = 0;
	while (b > 0)
	{
		lcd( b%10+48 );
		b = b / 10;
	}
	while (c%10 == 0)
	{
		c /= 10;
		lcd('0');
	}
}

void main(void)
{
   DDRB   = 0x05;
	DDRD   = 0x0F;
	PORTB  = 0xFF;
	PORTD  = 0xFF;
	SREG  |= 0x80;
	TIMSK |= 0x08;
	TCCR1B = 0xC1;

	lcd_init();
	lcd_text("I am ready!");
	
	while (bit_is_set(PINB,PB4));
	while(1)
	{
		while (TM == 0);
		unsigned int time = TM;
		
		unsigned long K = 3e7;
		AN = K / TM;
		if (2*(K%time) >= time) AN++;
		lcd_clear();
		lcd_num(AN);
		_delay_ms(500);

		if (bit_is_clear(PINB,PB4))
		{
			com = 0;
			lcd('+');
			_delay_ms(5);
			while (bit_is_clear(PINB,PB4));
			_delay_ms(5);
			while (bit_is_set(PINB,PB4));
			lcd_clear();
		}
	}
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.