/** * Name: Ash Zahabiuon * Date: 5/26/2024 * Assignment: Lab 2 * Youtube: https://youtu.be/9DWMKz36roA * * This program: * When ran, pressing the button cycles through different LED combinations: * RED -> GREEN -> RED & GREEN -> RED -> GREEN (loops). */ #include #include #define RED_LED_DIR P1DIR #define GREEN_LED_DIR P1DIR #define BUTTON_DIR P1DIR #define RED_LED_OUT P1OUT #define GREEN_LED_OUT P1OUT #define BUTTON_IN P1IN #define RED_LED_PIN BIT0 #define GREEN_LED_PIN BIT6 #define BUTTON_PIN BIT3 void initGPIO(void); bool isButtonPressed(void); void setRed(bool enable); void setGreen(bool enable); int main(void) { WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer initGPIO(); int ledState = 0; setRed(true); setGreen(false); for (;;) { if (isButtonPressed()) { ledState = (ledState + 1) % 3; switch (ledState) { case 0: setRed(false); setGreen(true); break; case 1: setRed(true); setGreen(true); break; case 2: setRed(true); setGreen(false); break; } while (isButtonPressed()); // Wait for button release } } } void initGPIO(void) { RED_LED_DIR |= RED_LED_PIN; // Set P1.0 to output direction GREEN_LED_DIR |= GREEN_LED_PIN; // Set P1.6 to output direction BUTTON_DIR &= ~BUTTON_PIN; // Set P1.3 to input direction P1REN |= BUTTON_PIN; // Enable pull-up/down resistor on P1.3 P1OUT |= BUTTON_PIN; // Set pull-up resistor on P1.3 setRed(false); setGreen(false); } bool isButtonPressed(void) { if (!(BUTTON_IN & BUTTON_PIN)) // If button is pressed { __delay_cycles(50000); // Debounce delay if (!(BUTTON_IN & BUTTON_PIN)) // If button is still pressed { return true; } } return false; } void setGreen(bool enable) { if (enable) { RED_LED_OUT |= RED_LED_PIN; } else { RED_LED_OUT &= ~RED_LED_PIN; } } void setRed(bool enable) { if (enable) { GREEN_LED_OUT |= GREEN_LED_PIN; } else { GREEN_LED_OUT &= ~GREEN_LED_PIN; } }