Skip to main content

Arduino 按鈕 code

const int N_BUTTONS = 7;
const int N_LIGHTS = 4;
const int button_pins[7] = {2,3,4,5,6,7,8};
const int light_pins[4] = {9, 10, 11, 12};

int last_button_state[7] = {0,0,0,0,0,0,0};
int physical_button_state[7] = {0,0,0,0,0,0,0};
int light_state[4] = {0, 0, 0, 0};
bool is_shooting = false;
unsigned long shooting_start = 10e6;

void read_physical_button_state(){
for(int i=0; i<N_BUTTONS; i++){
physical_button_state[i] = digitalRead(button_pins[i]);
}
}

int detect_change(){
// 0, 1, 2, 3 分別是每個燈泡個別亮暗
// 4, 5 全開 / 全關
// 6 計時模式

read_physical_button_state();
for(int i=0; i<N_BUTTONS; i++){
if(last_button_state[i] != physical_button_state[i]){
last_button_state[i] = physical_button_state[i];
return i;
}
}
return -1;
}

void setup(){
Serial.begin(9600);

for(int i=0; i<N_BUTTONS; i++){
pinMode(button_pins[i], INPUT_PULLUP);
}
for(int i=0; i<N_LIGHTS; i++){
pinMode(light_pins[i], OUTPUT);
}

read_physical_button_state();
for(int i=0; i<N_BUTTONS; i++){
last_button_state[i] = physical_button_state[i];
// Serial.print(last_button_state[i]);
// Serial.print(", ");
// Serial.print(physical_button_state[i]);
// Serial.print("\n");
}
}

void set_light_state(int pin, int state){
digitalWrite(light_pins[pin], state);
light_state[pin] = state;
}



void loop(){

int change = detect_change();

if(change >= 0){
Serial.println(change);
}

if(change == -1){
// no change
}else if((change >= 0 && change <= 3) && !is_shooting){
set_light_state(change, !light_state[change]);

}else if(change == 4){
// all open
for(int i=0; i<N_LIGHTS; i++){
set_light_state(i, HIGH);
}
is_shooting = false;
shooting_start = 10e6;
}
else if(change == 5){
// all close
for(int i=0; i<N_LIGHTS; i++){
set_light_state(i, LOW);
}
is_shooting = false;
shooting_start = 10e6;
}else if(change == 6){
// shooting
is_shooting = true;
shooting_start = millis();
}


if(is_shooting){
unsigned long now = millis();
if(now - shooting_start < 3000){
for(int i=0; i<N_LIGHTS; i++){
set_light_state(i, LOW);
}
}else if(now - shooting_start < 6000){
set_light_state(0, HIGH);
}else if(now - shooting_start < 8000){
set_light_state(0, LOW);
}else if(now - shooting_start < 11000){
set_light_state(0, HIGH);
}else if(now - shooting_start < 13000){
set_light_state(0, LOW);
}else if(now - shooting_start < 16000){
set_light_state(0, HIGH);
}else if(now - shooting_start < 18000){
set_light_state(0, LOW);
}else if(now - shooting_start < 21000){
set_light_state(0, HIGH);
}else if(now - shooting_start < 23000){
set_light_state(0, LOW);
}else if(now - shooting_start < 26000){
set_light_state(0, HIGH);
}else if(now - shooting_start < 29000){
set_light_state(0, LOW);
}else{
is_shooting = false;
shooting_start = 10e6;
set_light_state(0, LOW);
set_light_state(1, HIGH);
set_light_state(2, HIGH);
set_light_state(3, HIGH);
}
}
delay(300);
}