/*Mohammed Ali , Student ID: 300370238
Third exercise, Servo Oscillator when Button C is pressed

arduino uno. Component list as follows:

Button_a - Pin 2
Button_b - Pin 12
Button_c - Pin 8
Button_d - Pin 7

Amber LED - Pin5
Blue LED - Pin6
Green LED - Pin10
Red LED - Pin9

Servo - Pin 11 */

#include <Arduino.h>
#include <Servo.h> //calling the servo library so that the servo works and its features can be used
 
void yellowButton();
void greenButton();
void redButton();
void blueButton();

Servo myservo; //declared servo as myservo 

long randNum;
 int LEDcolour[]={5,6,9,10};
 int buttonPin[]={2,12,8,7};

int ledStatus[]={HIGH, HIGH, HIGH, HIGH};
int buttonStatus[]={LOW, LOW, LOW, LOW};

unsigned long previousTime=0;
unsigned long previousTimeLED[]={0,0,0,0}; 
const int servoInterval=8000;
const int blinkInterval=500;
static int servoPosition=0;



void setup(){



for (int i=0; i< 4; i++){
  pinMode(buttonPin [i], INPUT);
  pinMode(LEDcolour[i], OUTPUT);
  digitalWrite(LEDcolour[i],HIGH);
}
myservo.attach(11);
Serial.begin(9600);

attachInterrupt(digitalPinToInterrupt(2),redButton,RISING);

}

void loop(){
  unsigned long currentTime=millis();
  static int servoPosition = 0;

  //only execute this code when a certain time interval has elapsed
  if (currentTime - previousTime >= servoInterval) {
    if (servoPosition == 0) {
      myservo.write(9);     //set servo position to 9 degrees
    } else if (servoPosition == 1 || servoPosition == 3) {
      myservo.write(55);
    } else if (servoPosition == 2) {
      myservo.write(100);
    }

    servoPosition++;
    if (servoPosition == 4) {
      servoPosition = 0;
    }
    previousTime=currentTime;
  }
  /*if (servoPosition==0)
  Serial.println("HEY");

  if (currentTime-previousTime >= blinkInterval){
    previousTime=currentTime;
   if (ledStatus[9]== LOW)
{
  ledStatus[9]=HIGH;}
  else{
    ledStatus[9]=LOW;}
    digitalWrite(LEDcolour[9],ledStatus);
  }*/

if (digitalRead(buttonPin[1])==HIGH){
  greenButton();
}
if (digitalRead(buttonPin[2])==HIGH){
  blueButton();
}
if (digitalRead(buttonPin[3]) == HIGH){
  yellowButton();
}
}

void redButton(){
  Serial.println("RED INTERRUPT");

  for (int i=0;i < 4; i++){
    digitalWrite(LEDcolour[i], HIGH);

  }
  myservo.write(145);
}
 void blueButton(){
   Serial.println("BLUE BUTTON");
   //myservo.write(10);
unsigned long currentTime=millis();
   if (currentTime-previousTime >= servoInterval) {
     for(servoPosition=10; servoPosition<=120; servoPosition +=1){
       myservo.write(servoPosition);
     }
     previousTime=currentTime;
   }
 }
 
 void greenButton(){
   Serial.println("Green");
 }
 void yellowButton(){
   Serial.println("Yellow");
 }