/*
 * dynamics_data.ino
 *
 * Collects dynamics data (position) with
 * some varying (bounded) input PWM
 *
 * EE16B Fall 2016
 * John Maidens, Emily Naviasky & Nathaniel Mailoa
 *
 * EE16B Fall 2017
 * Andrew Blatner
 *
 * EE16B Spring 2019
 * Mia Mirkovic
 * 
 */

#define MOTOR                  P2_0
#define POT                    P6_0

float conversion_factor = 0;

void setup(void) {
  Serial.begin(38400);

  pinMode(MOTOR, OUTPUT);
  pinMode(POT, INPUT);
  conversion_factor = calibrate(); 
  Serial.print("Conversion factor: ");
  Serial.println(conversion_factor,DEC);
  Serial.print("Setup done\n");
  reset_blinker();

  write_pwm(0); // Turn off motor

  reset_blinker();
}

void loop(void) {

  int v_in = analogRead(POT); 
  float pwm = v_in*conversion_factor; 
  float duty_cycle = pwm/255*100;
  write_pwm(pwm); 
  Serial.print("Duty cycle: ");
  Serial.print(duty_cycle,DEC);
  Serial.println("%");
  
}

/*---------------------------*/
/*     Helper functions      */
/*---------------------------*/

void write_pwm(int pwm) {
  analogWrite(MOTOR, (int) min(max(0, pwm), 255));
}

void reset_blinker(void) {
  digitalWrite(RED_LED, HIGH);
  delay(100);
  digitalWrite(RED_LED, LOW);
  digitalWrite(GREEN_LED, HIGH);
  delay(100);
  digitalWrite(RED_LED, HIGH);
  digitalWrite(GREEN_LED, LOW);
  delay(100);
  digitalWrite(RED_LED, LOW);
  digitalWrite(GREEN_LED, HIGH);
  delay(100);
  digitalWrite(GREEN_LED, LOW);
}

float calibrate() {
  float max_sensor = analogRead(POT);
  float conversion_factor = 255/max_sensor;
  return conversion_factor;
  }
