Birdie小鸟套件 Arduino程序

#define PIN_R 3
#define PIN_G 5
#define PIN_B 6
#define PIN_TOUCH_1 A0
#define PIN_TOUCH_2 A1
#define PIN_INFRARED 4
#define PIN_SOUND 2

#define TOUCH_THRESHOLD 950

#define COLOR_BLUE 0
#define COLOR_ORANGE 1
#define COLOR_RED 2

#define TO_RED 1
#define TO_BLUE 0

int r_value = 255;
int g_value = 255;
int b_value = 0;//default color when start is blue

int current_color = COLOR_BLUE;

unsigned long touch_1_time = 0;
unsigned long touch_2_time = 0;

void setup() {
pinMode(PIN_R, OUTPUT);
pinMode(PIN_G, OUTPUT);
pinMode(PIN_B, OUTPUT);
pinMode(PIN_TOUCH_1, INPUT);
pinMode(PIN_TOUCH_2, INPUT);
pinMode(PIN_INFRARED, INPUT);
pinMode(PIN_SOUND, OUTPUT);

analogWrite(PIN_R, r_value);
analogWrite(PIN_G, g_value);
analogWrite(PIN_B, b_value);
digitalWrite(PIN_SOUND, HIGH);

Serial.begin(9600);
}

void loop() {
checkInfraredSensor();
checkTouchSensor();
}

void checkInfraredSensor(){
if (digitalRead(PIN_INFRARED)==LOW)//Someone comes close
digitalWrite(PIN_SOUND, LOW);
else
digitalWrite(PIN_SOUND, HIGH);
}

void checkTouchSensor(){
if(analogRead(PIN_TOUCH_1)>TOUCH_THRESHOLD){
boolean is_touch_constant = true;
for(int i=0;i<10;i++)
if(analogRead(PIN_TOUCH_1)<TOUCH_THRESHOLD){
is_touch_constant = false;
break;
}
if(is_touch_constant){
touch_1_time = millis();
}
}

if(analogRead(PIN_TOUCH_2)>TOUCH_THRESHOLD){
boolean is_touch_constant = true;
for(int i=0;i<10;i++)
if(analogRead(PIN_TOUCH_2)<TOUCH_THRESHOLD){
is_touch_constant = false;
break;
}
if(is_touch_constant){
touch_2_time = millis();
}
}

if((touch_2_time - touch_1_time)<1000&&(touch_2_time - touch_1_time)>10){
touch_1_time = 0;
touch_2_time = 0;
changeColor(TO_RED);
}
else if((touch_1_time - touch_2_time)<1000&&(touch_1_time - touch_2_time)>10){
touch_1_time = 0;
touch_2_time = 0;
changeColor(TO_BLUE);
}
}

void changeColor(int changeCode){
if(changeCode==TO_RED){
switch(current_color){
case COLOR_BLUE:
changeColorByValue(255, 97, 0);//RGB value of orange is 255, 97, 0
current_color = COLOR_ORANGE;
break;
case COLOR_ORANGE:
changeColorByValue(255, 0, 0);
current_color = COLOR_RED;
break;
case COLOR_RED:
break;
}
}
else{
switch(current_color){
case COLOR_BLUE:
break;
case COLOR_ORANGE:
changeColorByValue(0, 0, 255);
current_color = COLOR_BLUE;
break;
case COLOR_RED:
changeColorByValue(255, 97, 0);//RGB value of orange is 255, 97, 0
current_color = COLOR_ORANGE;
break;
}
}
}

void changeColorByValue(int final_r_value, int final_g_value, int final_b_value){
final_r_value = 255 - final_r_value;
final_g_value = 255 - final_g_value;
final_b_value = 255 - final_b_value;

int delta_r = (final_r_value - r_value)/ 30;
int delta_g = (final_g_value - g_value)/ 30;
int delta_b = (final_b_value - b_value)/ 30;

for(int i=0;i<30;i++){
r_value += delta_r;
g_value += delta_g;
b_value += delta_b;
analogWrite(PIN_R, r_value);
analogWrite(PIN_G, g_value);
analogWrite(PIN_B, b_value);
delay(10);
}

r_value = final_r_value;
g_value = final_g_value;
b_value = final_b_value;
}