Back to Parent

Completed Code
Servo myservo;// create servo object using the built-in Particle Servo Library

 int servoPin = D0;  //declare variable for servo
 int button = D1;    //declare variable for button
 int ledPin = D3;    //declare variable for led
 int redPin = A4;    // RED pin of the LED to PWM pin
 int greenPin = D4;  // GREEN pin of the LED to PWM pin
 int bluePin = D5;   // BLUE pin of the LED to PWM pin
 int count = 0;      //variable to keep track number of times the senser detects magnet
 int food = 0;

 void setup()
 {
   Particle.variable("count", &count, INT);
   //Sensor setup
   Serial.begin(19200);
   attachInterrupt(D2, magnet_detect,RISING);  //Initialize the intterrupt pin

   //Servo setup
   myservo.attach(D0);      //Initialize the servo attached to pin D0
   myservo.write(0);        //set servo to initial position
   delay(500);              //delay to give the servo time to move to its position
   myservo.detach();        //detach the servo to prevent it from jittering

   //LED setup
   pinMode( ledPin, OUTPUT);
   pinMode( redPin, OUTPUT);
   pinMode( greenPin, OUTPUT);
   pinMode( bluePin, OUTPUT);
   digitalWrite(ledPin, LOW);
   analogWrite( redPin, 255);
   digitalWrite( greenPin, 255);
   digitalWrite( bluePin, 255);
 }


 void loop()
 {
   if(count == 0){
     //RGB LED
     analogWrite( redPin, 255);
     digitalWrite( greenPin, 255);
     digitalWrite( bluePin, 0);   //turn on blue led
   }else if (count < 20){
     analogWrite( redPin, 0);   //turn on red led
     digitalWrite( greenPin, 255);
     digitalWrite( bluePin, 255);
   } else{
     //RGB LED
     analogWrite( redPin, 255);
     digitalWrite( greenPin, 0);   //turn on green led
     digitalWrite( bluePin, 255);

      if(food == 0)
      {
        // move servo
        myservo.attach(servoPin);
        myservo.write(180);
        delay(500);
        myservo.detach();

        //LED on
        digitalWrite( ledPin, HIGH);  //indicating servo move

        // reset servo
        delay(1000);
        myservo.attach(servoPin);
        myservo.write(0);
        delay(500);
        myservo.detach();
        digitalWrite( ledPin, LOW);

        food = 1;
       }
    }

   //Manually reset system
   if(digitalRead(button) == LOW) //if a button press has been detected...
    {
      count = 0;
      food = 0;
    }
 }


 void magnet_detect()//This function is called whenever a magnet/interrupt is detected
 {
   Serial.print(count);
   Serial.println("detect");
   count++;
 }
Tongtong Lu Click to Expand

Content Rating

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

0