Back to Parent

#include <Arduino_APDS9960.h>
#include <Servo.h> // include the servo library

Servo myservo;
int pos = 0;

void setup() {
  Serial.begin(9600);
  while (!Serial);

  if (!APDS.begin()) {
    Serial.println("Error initializing APDS-9960 sensor.");
  }
  myservo.attach(D2); // attach the servo to pin D2
  pos = myservo.read(); // get the initial position of the servo
}

void loop() {
  // check if a color reading is available
  while (! APDS.colorAvailable()) {
    delay(5);
  }
  int r, g, b;

  // read the color
  APDS.readColor(r, g, b);

  // print the values
  Serial.print("r = ");
  Serial.println(r);
  Serial.print("g = ");
  Serial.println(g);
  Serial.print("b = ");
  Serial.println(b);
  Serial.println();

  if (r > g && r > b) { // check if green is the dominant color
      Serial.println("Red light detected.");
      for (pos; pos <= 45; pos += 1) { // gradually turn the servo from current position to 30 degrees
        myservo.write(pos);
        delay(100);
      }
      delay(1000);
      myservo.write(45);
      //myservo.detach();
    }
    else if (g > r && g > b) { // check if red is the dominant color
      Serial.println("Green light detected.");
      for (pos; pos >= 0; pos -= 1) { // gradually turn the servo from current position to 0 degrees
        myservo.write(pos);
        delay(100);
      }
      delay(1000);
      myservo.write(0);
      //myservo.detach();
    }
    else { // any other color detected
      Serial.println("Other color detected.");
      for (pos; pos <= 30; pos += 1) { // gradually turn the servo from current position to 30 degrees
        myservo.write(pos);
        delay(100);
      }
      for (pos; pos >= 0; pos -= 1) { // gradually turn the servo from 30 to 0 degrees
        myservo.write(pos);
        delay(100);
      }
    }
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0