Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Last active December 21, 2017 02:43
Show Gist options
  • Save dcbriccetti/25c20ee7287fd813bae82934551f5ac9 to your computer and use it in GitHub Desktop.
Save dcbriccetti/25c20ee7287fd813bae82934551f5ac9 to your computer and use it in GitHub Desktop.
// Sketch for a servo that turns with the light intensity
// See video demo at https://youtu.be/BSZc9sFR4vs
#include <Servo.h>
const Servo myServo;
const int lightSensor = A0;
const int red = 7;
const int green = 8;
const int speaker = 6;
const int servo = 9;
const int lightsOnMs = 50;
const int lightSampleIntervalMs = 250;
void setup() {
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
myServo.attach(servo);
}
int lastSensorValue = 0;
void loop() {
const int sensorValue = analogRead(lightSensor);
if (abs(sensorValue - lastSensorValue) > 3) { // Avoid reacting to tiny changes
// Turn on green light if ascending, red light if descending
digitalWrite(sensorValue > lastSensorValue ? green : red, HIGH);
tone(speaker, map(sensorValue, 0, 1023, 20, 3000), 50);
int angle = map(sensorValue, 0, 1023, 0, 178); // Too high makes the motor stay buzzing
myServo.write(angle);
lastSensorValue = sensorValue;
}
delay(lightsOnMs);
digitalWrite(7, LOW);
digitalWrite(8, LOW);
delay(lightSampleIntervalMs - lightsOnMs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment