typestar

traffic_light.ino en Arduino

Un semáforo: fases en enum, transiciones a reloj, sin delay.

// A junction traffic light: state machine, no delay in sight.

const int RED_PIN = 4;
const int AMBER_PIN = 5;
const int GREEN_PIN = 6;

enum Phase { GO, CAUTION, STOP_ALL };
Phase phase = STOP_ALL;
unsigned long phaseStart = 0;

// How long each phase holds, in milliseconds.
unsigned long phaseLength(Phase p) {
  switch (p) {
    case GO:       return 6000;
    case CAUTION:  return 1500;
    case STOP_ALL: return 5000;
  }
  return 1000;
}

Phase nextPhase(Phase p) {
  switch (p) {
    case GO:       return CAUTION;
    case CAUTION:  return STOP_ALL;
    case STOP_ALL: return GO;
  }
  return STOP_ALL;
}

void showPhase(Phase p) {
  digitalWrite(RED_PIN, p == STOP_ALL ? HIGH : LOW);
  digitalWrite(AMBER_PIN, p == CAUTION ? HIGH : LOW);
  digitalWrite(GREEN_PIN, p == GO ? HIGH : LOW);
}

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(AMBER_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  showPhase(phase);
  phaseStart = millis();
}

void loop() {
  if (millis() - phaseStart >= phaseLength(phase)) {
    phase = nextPhase(phase);
    showPhase(phase);
    phaseStart = millis();
  }
}

Cómo funciona

  1. phaseLength y nextPhase vuelven el ciclo un par de tablas.
  2. showPhase mapea el estado sobre los tres pines en un lugar.
  3. El loop son cuatro líneas: mira el reloj, avanza, repinta.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
50
Caracteres a escribir
1036
Tokens
240
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 222 segundos.

Escribe este fragmento

Paso 1 de 3 en Bis; paso 25 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →