[FPGA] FPGA + AVR StopWatch

2021. 11. 12. 22:02코딩/FPGA

#define F_CPU	16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "button.h"

// fnd select PD0,PD1
// fnd bin PD2 ~ PD5

#define FND_SELECT_DDR	DDRD
#define FND_BIN_DDR		DDRD
#define FND_SELECT_PORT	PORTD
#define FND_BIN_PORT	PORTD
#define FND_PORT		PORTD

uint8_t fndDigit1Data;
uint8_t fndDigit2Data;
uint8_t fndDigit3Data;
uint8_t fndDigit4Data;

volatile uint16_t fndCounter = 0;
uint8_t state;

enum {STOP, RUN, RESET};

ISR(TIMER1_COMPA_vect)
{
	// 0.1초 간격으로 인터럽트 발생.
	
	fndDigit1Data = fndCounter % 10;
	fndDigit2Data = fndCounter / 10 % 10;
	fndDigit3Data = fndCounter / 100 % 10;
	fndDigit4Data = fndCounter / 1000 % 10;
	if (state == RUN)
	{
		fndCounter = (fndCounter+1) % 10000;
	}
}

ISR(TIMER0_COMP_vect)
{
	// 1ms 간격으로 인터럽트 발생.
	static uint8_t fndDist = 0;
	
	switch (fndDist)
	{
		case 0 : fndWrite(0, fndDigit1Data);
		break;
		case 1 : fndWrite(1, fndDigit2Data);
		break;
		case 2 : fndWrite(2, fndDigit3Data);
		break;
		case 3 : fndWrite(3, fndDigit4Data);
	}
	fndDist = (fndDist+1) % 4;
}

int main(void)
{
	FND_SELECT_DDR |= (1<<DDRD0) | (1<<DDRD1);
	FND_BIN_DDR |= (1<<DDRD2) | (1<<DDRD3) | (1<<DDRD4) | (1<<DDRD5);
	
	// TIM0
	TCCR0 |= (1<<WGM01); // CTC mode
	TCCR0 |= (1<<CS02); // prescaler 64
	OCR0 = 250 - 1;     // 1ms
	TIMSK |= (1<<OCIE0);
	
	// TIM1
	TCCR1B |= (1<<WGM12); // CTC 4 MODE
	TCCR1B |= (1<<CS11) | (1<<CS10); // prescaler 64
	OCR1A = 25000 - 1;  // 0.1초
	TIMSK |= (1<<OCIE1A);
	
	buttonInit();
	state = STOP;

	sei();
	
	while (1)
	{
		switch (state)
		{
			case STOP :
			if (getButton1State())
			{
				state = RUN;
			}
			else if (getButton2State())
			{
				state = RESET;
			}
			break;
			case RUN :
			if (getButton1State())
			{
				state = STOP;
			}
			break;
			case RESET : fndCounter = 0;
			state = STOP;
			break;
		}
	}
}

void fndWrite(uint8_t select, uint8_t bin)
{
	if (select >= 4) select = 3;
	if (bin > 10) bin = 10;
	FND_PORT = (bin<<2) | select; // xx xxxx xx
}

 

1번 버튼이 시작,정지

시작중 리셋버튼 작동X

정지시 리셋버튼 작동O