/*
#include <Servo.h>
#include <Streaming.h>
Print &cout {Serial};
enum class Direction : int8_t { up = 1, down = -1 };
namespace LightState {
constexpr uint8_t on {0};
constexpr uint8_t off {1};
}
namespace gc {
constexpr uint8_t servoPin {3};
constexpr uint8_t analogPin {A0};
constexpr int servoPos[2] {0, 90 };
constexpr uint32_t stepDelay_ms {5}; // Milliseconds
constexpr uint16_t threshold {700};
}
Servo servo;
int setServo(Servo &sv, uint16_t position, Direction dir, uint16_t stepDelay_ms = gc::stepDelay_ms) {
sv.write(position);
position += static_cast<int8_t>(dir);
delay(stepDelay_ms);
return position;
}
void checkLight(uint16_t aValue, uint16_t threshold, Servo &sv) {
uint16_t pos = sv.read();
uint16_t targetPos;
targetPos = (aValue < threshold) ? gc::servoPos[LightState::on] : gc::servoPos[LightState::off];
do { pos = setServo(sv, pos, (pos > targetPos) ? Direction::down : Direction::up); } while (pos != targetPos);
cout << _FMT("Analog Value: % -> Pos: %", _WIDTH(aValue, 4), _WIDTH(pos, 3)) << "\n";
}
void setup() {
Serial.begin(115200);
cout << "Start" << __FILE__ << endl;
servo.attach(gc::servoPin);
servo.write(gc::servoPos[LightState::off]);
}
void loop() {
static uint16_t prevLightValue {0};
uint16_t lightValue = analogRead(gc::analogPin);
if (lightValue != prevLightValue) {
prevLightValue = lightValue;
checkLight(lightValue, gc::threshold, servo);
}
}
*/
#include <Servo.h>
const int lichtSensorPin = A0; // Lichtsensor an Analogpin A0
const int schwelle = 700; // Schwellenwert für Licht an/aus (anpassen!)
const int servoPin = 3; // Servo an Digitalpin 3
Servo meinServo;
void setup() {
meinServo.attach(servoPin);
meinServo.write(90); // Startposition (Mittelstellung)
Serial.begin(9600);
}
void loop() {
int lichtWert = analogRead(lichtSensorPin);
Serial.println(lichtWert); // Debugging
if (lichtWert < schwelle) {
meinServo.write(0); // Licht an -> Servo nach links
delay(15); // Kurze Verzögerung, um die Bewegung zu stabilisieren
} else {
meinServo.write(90); // Licht aus -> Servo zurück zur Mittelstellung
delay(15); // Kurze Verzögerung für die Rückbewegung
}
delay(100); // Kleine Verzögerung zur Stabilisierung
}
Light is
Anklicken zum
Ändern der Entfernung
on
off