Skip to content

Instantly share code, notes, and snippets.

@brandocorp
Created August 2, 2020 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandocorp/aa879e1d5fd3631f47df5f146005065e to your computer and use it in GitHub Desktop.
Save brandocorp/aa879e1d5fd3631f47df5f146005065e to your computer and use it in GitHub Desktop.
Arduino Servo Motor and Photo Resistor Sensor
// http://www.bajdi.com/continuous-rotation-servos-and-arduino/
// Continuous Servo controls
// Counter clock-wise rotation is achieved using values from 45-89, fastest to slowest speed.
// Clock-wise rotation is achieved using values from 91-135, slowest to fastest speed.
// Servo Library
// https://www.arduino.cc/reference/en/libraries/servo/
#include <Servo.h>
Servo servo;
const int speedLow = 15;
const int speedMedium = 30;
const int speedHigh = 45;
const int lightSensorPin = 0;
const int servoPin = 9;
int lightValue;
int servoRotation;
void setup() {
Serial.begin(115200);
lightValue = analogRead(lightSensorPin);
}
// Rotate the servo clock
void clockwiseRotation(int speed){
int servoSpeed;
if ( speed > 45 ) {
speed = 45;
}
// 90 is speed 0;
servoSpeed = 90 + speed;
servo.attach(servoPin);
servo.write(servoSpeed);
delay(5000);
servo.write(90);
servo.detach();
}
void counterclockwiseRotation(int speed){
int servoSpeed;
if ( speed > 45 ) {
speed = 45;
}
// 90 is speed 0
servoSpeed = 90 - speed;
servo.attach(servoPin);
servo.write(servoSpeed);
delay(5000);
servo.write(90);
servo.detach();
}
void loop() {
lightValue = analogRead(lightSensorPin);
Serial.println(lightValue);
if ( lightValue > 35 ) {
Serial.println("Daytime");
clockwiseRotation(speedHigh);
} else {
Serial.println("Nightime");
counterclockwiseRotation(speedHigh);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment