/*
 *   Define pins
 */

// Four modes, these attach to the rotary switch
#define mode1p 7   // no hall program (chaotic)
#define mode2p 8   // hall program (brushless motor)
#define mode3p 9   // caotico-tico (chaotic with some preset parameters)
#define mode4p 10  // accelerando-ritardando (back and forth spinning)

// These go to the leds in the lid,
// showing the polarity (or accel/retard in mode 4)
#define pole1 11
#define pole2 12

// These go to the first motor channel for the electromagnet 
#define coil1 5
#define coil2 6
#define duty_pin 3 // This is the on-off signal to the motor driver

// These go to the second motor channel for the piezo
#define piezo1 A5
#define piezo2 A6

#define hall_pin 2 // This reads the Hall sensor
#define timer_pin A1     // This reads the timer potentiometer
#define throttle_pin A2  // This reads the throttle potentiometer
#define trimpotN_pin A3  // These two read the trimpots
#define trimpotS_pin A4  // on the breadboard


void hall_programme(void);
void no_hall_programme(void);
void caotico_tico(void);
void accelerando_ritardando(void);
void swap(void);
void duty(bool du);

bool on_duty;
bool swapper;

int mode;
unsigned long hall_time = 0;
unsigned long last_hall_time = 1;

void setup() {
    pinMode(coil1, OUTPUT);
    pinMode(coil2, OUTPUT);
    pinMode(pole1, OUTPUT);
    pinMode(pole2, OUTPUT);
    pinMode(A5, OUTPUT);
    pinMode(A6, OUTPUT);
    
    pinMode(LED_BUILTIN, OUTPUT);
    pinMode(mode1p, INPUT_PULLUP);
    pinMode(mode2p, INPUT_PULLUP);
    pinMode(mode3p, INPUT_PULLUP);
    pinMode(mode4p, INPUT_PULLUP);
  
  attachInterrupt(digitalPinToInterrupt(hall_pin), time_hall, FALLING);
}

void time_hall(void)
{
  hall_time = millis();
 
}

void loop() {
  if (digitalRead(mode1p) == LOW)
    mode = 1;
  if (digitalRead(mode2p) == LOW)
    mode = 2;
  if (digitalRead(mode3p) == LOW)
    mode = 3;
  if (digitalRead(mode4p) == LOW)
    mode = 4;
  
  switch (mode)
  {
    case 1 :
      no_hall_programme();
      break;
    case 2 :
      hall_programme();
      break;
    case 3 : 
      caotico_tico();
      break;
    case 4 :
      accelerando_ritardando();
      break;
    default :
      break;
  }
}
