Arduino - LED計數器(LED Counter)


材料:
1.LED*4

2.電阻*4

3.開關*1


目的:

2進制計數器,開關按一次值+1,超過15歸0


成果:


Arduino Code:


const byte LED[4] = {
    8,
    9,
    10,
    11
};
boolean lastState = LOW;
byte time[4] = {
    0
};

void setup() {
    Serial.begin(9600);
    pinMode(LED[0], OUTPUT);
    pinMode(LED[1], OUTPUT);
    pinMode(LED[2], OUTPUT);
    pinMode(LED[3], OUTPUT);
    pinMode(2, INPUT);
    digitalWrite(2, HIGH);
}

void loop() {
    boolean now = digitalRead(2);
    Serial.print(now);
    if (now == HIGH && lastState == LOW) {
        Serial.println(time[0]);
        time[0]++;
        for (int i = 0; i < 4; i++) {
            if (time[i] >= 2) {
                time[i] = 0;
                time[i + 1]++;
                if (time[3] >= 2) {
                    for (int i = 0; i < 4; i++) {
                        time[i] = 0;
                    }
                }
            }
        }
        for (int i = 0; i < 4; i++) {
            if (time[i] == 1) {
                digitalWrite(LED[i], HIGH);
            } else if (time[i] == 0) {
                digitalWrite(LED[i], LOW);
            }
        }
    }
    delay(100);
}

留言