//Bit manipulation macros
 
#define BIT_SET(value,bitno)    ( (value) |= (1<<(bitno)))
 
#define BIT_CLEAR(value,bitno)  ( (value) &= ~(1<<(bitno)))
 
 
 
#include <avr/io.h>
 
#include <stdio.h>
 
#include "USART.h"
 
#include <util/delay.h>
 
#include "ADC.h"
 
 
 
FILE fpUSART = FDEV_SETUP_STREAM(USARTSendByte, USARTGetByte, _FDEV_SETUP_RW);
 
 
 
// Sets up Timer 1 for fast-PWM operation
 
// DC-Motor Connected to PB0 and OSC1A (PB1)
 
void init_PWM_OSC1A()
 
{
 
        TCCR1A = (1<<COM1A1) | (1<<WGM11);     // Clear on compare, fast PWM, TOP=ICR1 (WGM13/WGM12 in TCCR1B)
 
        TCCR1B = (1<<WGM12)  | (1<<WGM13) ;                   // CTC-mode width ICR1 defines the TOP'value
 
        TCCR1B |=(1<< CS11)  | (1<<CS10);                     // Prescaler 64
 
 
 
        ICR1 = 5000;    //- Input Capture Register In PWM mode this register defines the TOP period
 
        OCR1A = 0;      // Start width no pulse
 
}
 
 
 
void rotateClockwise(int Speed)
 
{
 
        //Clear OC1A on Compare Match,
 
        //set OC1A at BOTTOM (non-inverting mode)
 
        BIT_CLEAR(TCCR1A,COM1A0);
 
        BIT_SET(TCCR1A,COM1A1);
 
 
 
        BIT_CLEAR(PORTB,PB0);  //Clear bit 0 PORTB (PB0)
 
        OCR1A=Speed;
 
}
 
 
 
void rotateCounterClockwise(int Speed)
 
{
 
        //Clear OC1A on Compare Match,
 
        //set OC1A at BOTTOM (non-inverting mode)
 
        BIT_CLEAR(TCCR1A,COM1A0);
 
        BIT_SET(TCCR1A,COM1A1);
 
 
 
        BIT_SET(PORTB,PB0);  //Clear bit 0 PORTB (PB0)
 
        OCR1A=5000-Speed;
 
}
 
 
 
// A DC Motor is connected to PB0 and OSC1A (PB1)
 
// DIGITAL-8 and DIGITAL-9 on the Arduino Uno Board
 
// The program rotates the motor slowly clockwise
 
int main(void)
 
{
 
        int ADCverdi;
 
        int fart;
 
        init_PWM_OSC1A();
 
        init_USART();
 
        InitADC();
 
        stdin=&fpUSART;
 
        stdout=&fpUSART;
 
        DDRB =  (1 << PB1) | (1<<PB0);
 
 
 
        DDRC = (1 << PC0) | (1 << PC2);
 
        PORTC &= ~(1<<PC2);
 
        PORTC = (1<<PC0);
 
 
 
    while(1)
 
        {
 
                ADCverdi = ReadADC(1);
 
                _delay_ms(50);
 
                if (ADCverdi < 500)
 
                {
 
                        fart = (500 - ADCverdi)*9;
 
                        rotateClockwise(fart);
 
                }
 
                if (ADCverdi > 520)
 
                {
 
                        fart = (ADCverdi - 520)*9;
 
                        rotateCounterClockwise(fart);
 
                }
 
                if(ADCverdi > 500 && ADCverdi < 520)
 
                {
 
                        rotateClockwise(0);
 
                }
 
                printf("%d \n\r", fart);
 
        }
 
}