Unit 11: Digital Numbers

 

 

Correct Image:

(The green lead goes to 5V not GND)

Code: 


#include 

// Define the connections pins for the TM1637 4-digit display
#define CLK 3
#define DIO 2

GyverTM1637 display(CLK, DIO);

// Define the button pin
const int buttonPin = 4;

// Variable to count button presses
int count = 0;

// Variable to store the button state
int lastButtonState = HIGH;

void setup() {
  // Initialize the TM1637 display
  display.clear();
  display.brightness(7);  // Set brightness to maximum

  // Initialize button pin as input with internal pull-up resistor
  pinMode(buttonPin, INPUT_PULLUP);

  // Display initial count
  display.displayInt(count);
}

void loop() {
  // Read the current state of the button
  int buttonState = digitalRead(buttonPin);

  // Check if the button is pressed (LOW state) and was previously not pressed
  if (buttonState == LOW && lastButtonState == HIGH) {
    delay(50);  // Debounce delay
    if (digitalRead(buttonPin) == LOW) {
      count++;  // Increment count
      display.displayInt(count);  // Display the new count
    }
  }

  // Update the last button state
  lastButtonState = buttonState;
}

  

Commented Challenge: 


  
#include <>

// Define pins for TM1637 display
const int CLK_PIN = 3;
const int DIO_PIN = 2;

// Create display object
GyverTM1637 display(CLK_PIN, DIO_PIN);

// Define pin for the button
const int BUTTON_PIN = 4;

// Variables to store the count and button state
int count = 0;
int buttonState = HIGH;
int lastButtonState = HIGH;
const int FACTOR1 = 179;
const int FACTOR2 = 37;
const int OFFSET = 5000;
const int OBSCURED_NUM = (FACTOR1 * FACTOR2) - OFFSET;

void setup() {
  // Initialize the display
  display.clear();
  display.brightness(7);
  // Initialize button pin
  pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
  // Read the button state
  buttonState = digitalRead(BUTTON_PIN);
  // Check if the button is pressed
  if (buttonState == LOW && lastButtonState == HIGH) {
    count++;
    display.displayInt(count);
    delay(200); // Debounce delay
  } 
  // Check if the button is held for more than 3 seconds and count is 9
  if (buttonState == LOW && lastButtonState == LOW && count == 9) {
    delay(3000); // Wait for 3 seconds
    if (digitalRead(BUTTON_PIN) == LOW) {
      // Compute and display the hidden number 6623
      int hiddenNumber = OBSCURED_NUM + OFFSET;
      display.displayInt(hiddenNumber);
    }
  } 
  // Reset display when button is released
  if (buttonState == HIGH && lastButtonState == LOW && count == 9) {
    display.displayInt(count);
  }
  // Update the last button state
  lastButtonState = buttonState;
}

 

Notes: 

Use the display library by writing: #include <gyvertm1637.h> at the top of the sketch. This page treats it as instruction, so will not let us show it in the main code itself.