Created
October 3, 2012 23:10
-
-
Save michelleboisson/3830481 to your computer and use it in GitHub Desktop.
Arduino Servo and light sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> // include the servo library | |
Servo servoMotor; // creates an instance of the servo object to control a servo | |
int servoPin = 2; // Control pin for servo motor | |
int pos = 0; // variable to store the servo position | |
int now, previousTime, interval = 0; | |
//for smoothing of values | |
const int numReadings = 10; | |
int readings[numReadings]; // the readings from the analog input | |
int index = 0; // the index of the current reading | |
int total = 0; // the running total | |
int average = 0; // the average | |
void setup() { | |
Serial.begin(9600); // initialize serial communications | |
servoMotor.attach(servoPin); // attaches the servo on pin 2 to the servo object | |
for (int thisReading = 0; thisReading < numReadings; thisReading++) | |
readings[thisReading] = 0; | |
} | |
void loop() | |
{ | |
int lightValue = getSmoothValue(); | |
Serial.println(lightValue); // print it | |
if (lightValue < 100){ | |
now = millis(); | |
if(now - previousTime > 5000){ | |
startKnocking(); | |
//timer.setInterval(10000, startKnocking); | |
} | |
} | |
else if (lightValue > 100){ | |
previousTime = millis(); | |
stopKnocking(); | |
} | |
} | |
void startKnocking(){ | |
for(pos = 0; pos < 90; pos += 5) // goes from 0 degrees to 180 degrees | |
{ // in steps of 1 degree | |
servoMotor.write(pos); // tell servo to go to position in variable 'pos' | |
delay(5); // waits 15ms for the servo to reach the position | |
} | |
for(pos = 90; pos>=1; pos-=5) // goes from 180 degrees to 0 degrees | |
{ | |
servoMotor.write(pos); // tell servo to go to position in variable 'pos' | |
delay(5); // waits 15ms for the servo to reach the position | |
} | |
} | |
void stopKnocking(){ | |
Serial.println("____________________STOP_____________"); | |
servoMotor.write(0); | |
} | |
int getSmoothValue(){ | |
// subtract the last reading: | |
total= total - readings[index]; | |
// read from the sensor: | |
readings[index] = analogRead(A0); | |
// add the reading to the total: | |
total= total + readings[index]; | |
// advance to the next position in the array: | |
index = index + 1; | |
// if we're at the end of the array... | |
if (index >= numReadings) | |
// ...wrap around to the beginning: | |
index = 0; | |
// calculate the average: | |
average = total / numReadings; | |
// send it to the computer as ASCII digits | |
return average; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment