CCCPaste

Control Panel rev_01

/********* 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: Control Panel
	- Source Code NOT compiled for: Arduino Uno
	- Source Code created on: 2025-10-27 11:44:44

********* 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 */
/****** END SYSTEM REQUIREMENTS *****/


/* START CODE */

#include 

// Pin definitions
const int BTN_UP = 2;
const int BTN_DOWN = 3;
const int BTN_RESET = 4;
const int SWITCH_MODE = 5;
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;

// Function prototypes
void updateLEDs();
int binaryToGray(int num);

void setup() {
  // Set input pins with internal pull-up
  pinMode(BTN_DOWN, INPUT_PULLUP);
  pinMode(BTN_UP, INPUT_PULLUP);
  pinMode(BTN_RESET, INPUT_PULLUP);
  pinMode(SWITCH_MODE, INPUT_PULLUP);

  // Set output pins for LEDs
  pinMode(LED_MSB, OUTPUT);
  pinMode(LED_LSB, OUTPUT);

  // Initialize LEDs
  digitalWrite(LED_MSB, LOW);
  digitalWrite(LED_LSB, LOW);
}

void loop() {
  // Read mode switch
  grayMode = (digitalRead(SWITCH_MODE) == LOW);

  // Increment button
  if (digitalRead(BTN_UP) == LOW && millis() - lastPress > debounceDelay) {
    counter++;
    if (counter > 3) counter = 0;  // Counter modulo 4
    ledsActive = true;
    lastPress = millis();
    updateLEDs();
  }

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

  // Reset button
  if (digitalRead(BTN_RESET) == LOW && millis() - lastPress > debounceDelay) {
    counter = 0;
    ledsActive = false;
    lastPress = millis();
    updateLEDs();
  }
}

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);
}

int binaryToGray(int num) {
  return num ^ (num >> 1);
}

/* END CODE */