# Midterm: Little Bird Pet

The little bird jumps all the time. If you feed her by clicking the colorful ball, she will sing happily. But if you get closer, she will jump crazily and scream.

There’s a photoresistor, a flex sensor and a servo inside.

Code:

#include <Servo.h>

Servo myservo1; //360
int val1 = 0;
int val2 = 0;
int t1 = 80;
int t2 = 120;

int pos = 0;
int pos_l = 20;
int dir = 1;

int toneSpeed = 1800;
int speakerPin = 7;
int freq = 2000;
int feed = 2200;

int lightPin = 0;
int flexPin = 1;
int flexVal = 0;

void setup() {
myservo1.attach(9);
Serial.begin(9600);
pinMode(speakerPin, OUTPUT);
}
void loop() {
//Serial.println(val1);
val1 = map(val1, 300, 800, 0, 180);
// Serial.println(val1);

Serial.println(flexVal);

if(flexVal < 8) {
tone(speakerPin, feed+flexVal*5, 8);
delay(10);
tone(speakerPin, feed+flexVal*5-150, 16);
noTone(speakerPin);
}

if(val1 <= t1) {
pos += 2 * dir;
noTone(speakerPin);
if(pos < pos_l) {
pos = pos_l;
dir *= -1;
}
else if(pos > pos_l+60) {
pos = pos_l+60;
dir *= -1;
}
}
else if(val1 > t1 && val1 <= t2) {
pos += 4 * dir;
noTone(speakerPin);

if(pos < pos_l) {
pos = pos_l;
dir *= -1;
}
else if(pos > pos_l+60) {
pos = pos_l+60;
dir *= -1;
}
}
else if(val1 > t2) {
pos += 5 * dir;
tone(speakerPin, freq+val1*5);
if(pos < pos_l) {
pos = pos_l;
dir *= -1;
}
else if(pos > pos_l+30) {
pos = pos_l+30;
dir *= -1;
}
}
// Serial.println(pos);
myservo1.write(pos);
delay(10);
}