Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Global Vars
- int UP = 1;
- int DOWN = 0;
- int STOP = 2;
- int UNKNOWN = 2;
- int LightLevel = 0;
- int DoorState = 2; // assume neither open nor closed
- unsigned long motorstarttime;
- // Pin Assignments
- int MotorPinA = 0;
- int LEDPin = 1;
- int MotorPinB = 2;
- int TopSwPin = 3; // has internal 1.5k pull-up
- int BottomSwPin = 4;
- int PhotoRPin = 0; // is actually pin 5 (analog fuckery)
- void setup(){
- // pinMode(PhotoRPin, INPUT); // dont do this -- i dont' know why
- pinMode(MotorPinA, OUTPUT);
- pinMode(MotorPinB, OUTPUT);
- pinMode(LEDPin, OUTPUT);
- pinMode(TopSwPin, INPUT);
- pinMode(BottomSwPin, INPUT);
- digitalWrite(MotorPinA, HIGH); // motor triggers on LOW
- digitalWrite(MotorPinB, HIGH); // motor triggers on LOW
- digitalWrite(LEDPin, LOW);
- DoorState = GetDoorState();
- if (DoorState == UNKNOWN) {
- OpenDoor();
- }
- }
- void loop() {
- // Get current light level
- LightLevel = analogRead(PhotoRPin)/4; // low is dark, high is light
- if (LightLevel < 20) { // It's dark
- CloseDoor();
- }
- else if (LightLevel > 55) { // It's light
- OpenDoor();
- }
- delay(2000);
- }
- void OpenDoor() {
- motorstarttime = millis();
- DoorState = GetDoorState();
- while (DoorState != UP) {
- MotorControl(UP);
- DoorState = GetDoorState();
- if (millis() - motorstarttime > 15000) { break; } // Stop running the motor if 15 seconds has passed
- }
- MotorControl(STOP);
- }
- void CloseDoor() {
- motorstarttime = millis();
- DoorState = GetDoorState();
- while (DoorState != DOWN) {
- MotorControl(DOWN);
- DoorState = GetDoorState();
- if (millis() - motorstarttime > 15000) { break; } // Stop running the motor if 15 seconds has passed
- }
- delay(50);
- MotorControl(STOP);
- }
- void MotorControl(int Direction) {
- if (Direction == UP) {
- digitalWrite(MotorPinA, LOW);
- digitalWrite(MotorPinB, HIGH);
- } else if (Direction == DOWN) {
- digitalWrite(MotorPinA, HIGH);
- digitalWrite(MotorPinB, LOW);
- } else if (Direction == STOP) {
- digitalWrite(MotorPinA, HIGH);
- digitalWrite(MotorPinB, HIGH);
- }
- }
- int GetDoorState() {
- // Read switch states
- int topSwStatus = digitalRead(TopSwPin);
- int bottomSwStatus = digitalRead(BottomSwPin);
- int returnValue = UNKNOWN;
- // check to see if the door is between states
- if ((topSwStatus == 1) and (bottomSwStatus == 0)) { returnValue = UNKNOWN; }
- // check to see if the door is open
- if (topSwStatus == 0) { returnValue = UP; }
- // check to see if the door is closed
- if (bottomSwStatus == 1) { returnValue = DOWN; }
- return(returnValue);
- }
- void BlinkLED(int times) {
- for (int i=1; i <= times; i++) {
- digitalWrite(LEDPin, HIGH);
- delay(500);
- digitalWrite(LEDPin, LOW);
- delay(500);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment