Last active
November 30, 2016 14:58
-
-
Save lilykonings/e6c03b7d7d463ba3e53ffc9c975e62e2 to your computer and use it in GitHub Desktop.
intro to arduino: wagging a dog tail
This file contains hidden or 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> | |
int servoPin = 9; | |
int neutral = 0; | |
int happy = 1; | |
int scared = 2; | |
int attentive = 3; | |
class Dog { | |
Servo servo; | |
int state; | |
public: | |
Dog() { | |
state = neutral; | |
} | |
void Attach(int pin) { | |
servo.attach(pin); | |
} | |
void Detach() { | |
servo.detach(); | |
} | |
void Default() { | |
servo.write(40); | |
} | |
void Happy() { | |
int angle; | |
for(angle = 130; angle < 180; angle++) { | |
servo.write(angle); | |
delay(10); | |
} | |
for(angle = 180; angle > 130; angle--) { | |
servo.write(angle); | |
delay(10); | |
} | |
} | |
void Scared() { | |
servo.write(0); | |
} | |
void Attentive() { | |
servo.write(110); | |
} | |
}; | |
Dog spike; | |
void setup() { | |
Serial.begin(9600); | |
spike.Attach(servoPin); | |
spike.Default(); | |
} | |
void loop() { | |
if (spike.state == happy) { | |
spike.Happy(); | |
} else if (spike.state == scared) { | |
spike.Scared(); | |
} else if (spike.state == attentive) { | |
spike.Listen(); | |
} else { | |
spike.Default(); | |
} | |
} | |
void serialEvent() { | |
while (Serial.available()) { | |
int new_state = Serial.parseInt(); | |
if (Serial.read() == '\n') { | |
spike.state = new_state; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment