CCCPaste

Counter Display rev_02

/********* Pleasedontcode.com **********

	Pleasedontcode thanks you for automatic code generation! Enjoy your code!

	- Terms and Conditions:
	You have a non-exclusive, revocable, worldwide, royalty-free license
	for personal and commercial use. Attribution is optional; modifications
	are allowed, but you're responsible for code maintenance. We're not
	liable for any loss or damage. For full terms,
	please visit pleasedontcode.com/termsandconditions.

	- Project: Counter Display
	- Source Code NOT compiled for: Arduino Uno
	- Source Code created on: 2025-10-27 11:51:55

********* Pleasedontcode.com **********/

/****** SYSTEM REQUIREMENTS *****/
/****** SYSTEM REQUIREMENT 1 *****/
	/* realizza un contatore up/down che conta sia */
	/* tramite codice gray che binario, alternandoli */
	/* tramite un deviatore. Ci sono 3 pulsanti, */
	/* incremento, decremento e reset, dettati */
	/* dall'utente, */
/****** END SYSTEM REQUIREMENTS *****/


/* START CODE */

// Definitions of button and switch pins
const int BTN_UP = 2;
const int BTN_DOWN = 3;
const int BTN_RESET = 4;
const int SWITCH_MODE = 5;

// LED output pins
const int LED_MSB = 6;
const int LED_LSB = 7;

// Variables
int counter = 0;
bool grayMode = false;
bool ledsActive = false;
unsigned long lastPress = 0;
const unsigned long debounceDelay = 200;

// Setup function
void setup() {
  // Imposta ingressi con pull-up interno
  pinMode(BTN_DOWN, INPUT_PULLUP);
  pinMode(BTN_UP, INPUT_PULLUP);
  pinMode(BTN_RESET, INPUT_PULLUP);
  pinMode(SWITCH_MODE, INPUT_PULLUP);

  // Imposta uscite per i LED
  pinMode(LED_MSB, OUTPUT);
  pinMode(LED_LSB, OUTPUT);

  // LED inizialmente spenti
  digitalWrite(LED_MSB, LOW);
  digitalWrite(LED_LSB, LOW);
}

// Loop function
void loop() {
  // Lettura deviatore modalità
  grayMode = (digitalRead(SWITCH_MODE) == LOW);

  // Pulsante incremento
  if (digitalRead(BTN_UP) == LOW && millis() - lastPress > debounceDelay) {
    counter++;
    if (counter > 3) counter = 0;
    ledsActive = true;
    lastPress = millis();
    updateLEDs();
  }

  // Pulsante decremento
  if (digitalRead(BTN_DOWN) == LOW && millis() - lastPress > debounceDelay) {
    counter--;
    if (counter < 0) counter = 3;
    ledsActive = true;
    lastPress = millis();
    updateLEDs();
  }

  // Pulsante reset
  if (digitalRead(BTN_RESET) == LOW && millis() - lastPress > debounceDelay) {
    counter = 0;
    ledsActive = false;
    lastPress = millis();
    updateLEDs();
  }
  delay(10);
}

// Update LEDs
void updateLEDs() {
  if (!ledsActive) {
    digitalWrite(LED_MSB, LOW);
    digitalWrite(LED_LSB, LOW);
    return;
  }
  int value = counter;
  if (grayMode) {
    value = binaryToGray(counter);
  }
  digitalWrite(LED_MSB, (value >> 1) & 1);
  digitalWrite(LED_LSB, (value >> 0) & 1);
}

// Conversione Binario → Gray
int binaryToGray(int num) {
  return num ^ (num >> 1);
}

/* END CODE */