Week 9: Analog and Digital switch

Stopwatch

Concept: 

The concept of this circuit is pretty straightforward, it’s a stopwatch! You specify the number of seconds you want the stopwatch to count by setting the potentiometer to a number on a scale of 1-60. Then you press on the red button. The LEDs start lighting in an alternating pattern that represents the seconds passed. When the time specified has passed both LEDs turn off.

Process & Highlights:

The potentiometer is connected in series with the analog input and is used to set the countdown time. The switch is connected in parallel and is used to start the countdown. The LEDs are connected in parallel with resistors and are used to display the countdown time. One LED indicates even seconds, and the other indicates odd seconds and it varies each time depending on the previous state.

Here is a video demo of the switch:

Code:

const int potentiometerPin = A0;
const int switchPin = 2;
const int ledPin1 = 3;
const int ledPin2 = 4;

int countdownTime = 0;
bool countdownStarted = false;

void setup() {
  pinMode(potentiometerPin, INPUT);
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (!countdownStarted) {
    countdownTime = map(analogRead(potentiometerPin), 0, 1023, 1, 60); // Set countdown time based on potentiometer
    Serial.println(countdownTime);
  }

  if (digitalRead(switchPin) == LOW) {
    countdownStarted = true;
  }

  if (countdownStarted && countdownTime > 0) {
    countdownTime--;
    displayCountdown();
    delay(1000); // One-second delay
  } else if (countdownTime == 0) {
    // Countdown finished
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    countdownStarted = false;
  }
}

void displayCountdown() {
  int ledState = (countdownTime % 2 == 0) ? HIGH : LOW; // Toggle LED state
  digitalWrite(ledPin1, ledState);
  digitalWrite(ledPin2, !ledState);
}

Reflections:

I found this exercise a bit harder than the first one but it was fun to implement. If I could change one thing about my circuit, it would be to maybe have a screen display the seconds that have elapsed as well. I would love to create more advanced circuits in the future and find a way to incorporate more creativity within.

Leave a Reply