
/**************************************************************************
Name            - detect_rotor
Parameters      - a rotor structure
Responsibility  - determine if there is an azmith and/or elevation rotor 
                  present.
                
Notes           - This feaure is here to allow a single rotor to be used if
                  desired.
                  This function will alter the rotor(s) bearing but the non
                  volatile memory data (EEPROM) will not be updated.
                
Returns         - Nothing
                  But sets the "type" variable in the rotor structure to 'P' 
                  if a pulse type rotor is detected.
                  Otherwise it sets it to zero (0).
Author          - Bill (N9CX)
**************************************************************************/

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <avr/eeprom.h>

#include "switches.h"
#include "lcd.h"
#include "main.h"
#include "sw_timers.h"

void detect_rotor(struct rotor *p_rotor){
    switch(p_rotor->detect_submode){
      case START:
        // turn on the motor and see if a pulse or timeout occurs 
        p_rotor->pulse_timer = PULSE_TIMEOUT;
        p_rotor->pwr_ctl(p_rotor, PWR_CW);
        p_rotor->detect_submode = MOVING_CW;
        break;
      case MOVING_CW:
        if(p_rotor->new_pulse){
            p_rotor->pwr_ctl(p_rotor, PWR_OFF);
            p_rotor->type = 'P';
            sw_timer5 = 500;
            p_rotor->detect_submode = HOLD_DISPLAY;
        }
        else if(p_rotor->limit == CW){
            p_rotor->limit = 0;
            p_rotor->pwr_ctl(p_rotor, PWR_OFF);
            p_rotor->wait = 200; 
            p_rotor->detect_submode = WAITING;
        }
        break;
      case WAITING:
        if(!p_rotor->wait){
            p_rotor->pwr_ctl(p_rotor, PWR_CCW);
            p_rotor->detect_submode = MOVING_CCW;
        }
        break;
      case MOVING_CCW:
        if(p_rotor->new_pulse){
            p_rotor->pwr_ctl(p_rotor, PWR_OFF);
            p_rotor->type = 'P';
            sw_timer5 = 500;
            p_rotor->detect_submode = HOLD_DISPLAY;
        }
        else if(p_rotor->limit == CCW){
            p_rotor->limit = 0;
            p_rotor->pwr_ctl(p_rotor, PWR_OFF);
            p_rotor->type = 0;
            sw_timer5 = 500;
            p_rotor->detect_submode = HOLD_DISPLAY;
        }
        break;
    case HOLD_DISPLAY:
        if(!sw_timer5){
            p_rotor->limit = 0;
            p_rotor->detect_submode = DONE;
        }
        break;
      case DONE:
            p_rotor->limit = 0;
            p_rotor->pulse_timer = PULSE_TIMEOUT;
        break;
    }
}
