/*======================================================================================
Project : DC모터드라이버 확장보드를 이용한 DC모터 제어하기 
Version : 
Date    : 2011-07-28
Author  : Kyung Nam Lee
Company : LKEMBEDDED 
Compiler: CodevisionAVR + AVRStudio
Comment: DC모터가 정회전 역회전 하는 프로그램이다. 

※※주의사항※※
10p 플랫 케이블을 아래와 같이 연결해주세요!
ATmega2560 확장형 개발보드 PORTC <------------->DC모터드라이버 확장보드 - 10핀 박스헤더 커넥터 (PORT1)
======================================================================================*/
#include <mega2560.h>
#define CW1 PORTC.0
#define CWC1 PORTC.1
#define CW2 PORTC.2
#define CCW2 PORTC.3
#define EN1 PORTC.4
#define EN2 PORTC.5
unsigned int duty=0;
unsigned int MotorDir=0;
// Timer 0 overflow interrupt service routine
interrupt [TIM0_OVF] void timer0_ovf_isr(void)
{
    static unsigned int cnt,cnt2=0;
    cnt++;cnt2++;     
    if(cnt==duty)
    {
      EN1=EN2=0;
    }   
    if(cnt==50)
    {
      EN1=EN2=1;   
      cnt=0;
    }    
    if(cnt2==500)
    {
        duty++; 
        if(duty>50) 
        {
            duty=0; 
            duty=1;// pwm pluse의 initialization value
            MotorDir^=1;  //direction Select variable value 
         
        }
        cnt2=0;
    }
    TCNT0+=0x06;
}

void main(void)
{
// Port C initialization
PORTC=0x00; // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In 
DDRC=0xff;  // State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T 

TCCR0A=0x00;//Normal Mode Operation(Overflow Interrupt Enable) 
TCCR0B=0x03;//64Prescale Select
TCNT0=0x06;// Timer/Count Register initialization

TIMSK0=0x01;// Timer(s)/Counter(s) Interrupt(s) initialization
#asm("sei")// Global enable interrupts
duty=1;// pwm pluse의 initialization value
while (1)
      {
        switch(MotorDir)
        {
        case 0: CW1=1;CWC1=0;CW2=1;CCW2=0;break; //forward direction
        case 1: CW1=0;CWC1=1;CW2=0;CCW2=1;break; //reverse direction      
        }     
        
   
      };
}
